API Response Error Handling
Define an APIError class that extends Error, which can be used to standardize the handling of erroneous HTTP responses from a RESTful API.
class APIError extends Error {
constructor(message, status) {
super(message);
this.name = this.constructor.name;
this.status = status;
}
}
Defines an APIError class that extends the built-in Error class, adding a `status` property to hold the HTTP status code associated with the error.
function handleResponse(response) {
if (!response.ok) {
return response.json().then(errorData => {
throw new APIError(errorData.message || 'Unknown error', response.status);
});
}
return response.json();
}
Defines a function to handle a fetch response. If the response is not ok (status code is not in the range 200-299), it attempts to parse the response as JSON and throws an APIError with the parsed error message and the status code.
fetch('https://api.example.com/data')
.then(handleResponse)
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
if (error instanceof APIError) {
console.error('API Error:', error.message, 'Status:', error.status);
} else {
console.error('Unexpected Error:', error);
}
});
Demonstrates how to use fetch to make a request to an API endpoint and how to handle success and error responses. The `handleResponse` function processes the response, and in the event of an error, it's caught and logged differently based on whether it's an instance of APIError or an unexpected error.