JavaScript
Public
Fetch JSON with Error Handling
Fetch JSON data and handle HTTP errors cleanly.
#javascript
#fetch
#json
#error-handling
JavaScript
async function loadProfile() {
const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
}
loadProfile()
.then(profile => console.log(profile))
.catch(error => console.error(error.message));
Notes
fetch only rejects on network errors, so check response.ok for HTTP errors.