I am doing an API fetch and when the fetch fails the server returns an error object I would like to include in my error message to user. I have tried variations of:
.then((response) => {
if (!response.ok) {
throw new Error(response);
}
return response.json();
})
.then((data) => {
// stuff if fetch succesful
.catch((error) => {
aiConversation.value = `I'm sorry. There was a problem with your request at this time. ${error.message}`;
The server is returning an object called error with a property message. How can I access the response object from server in the catch?
2
Answers
This is totally dependent on the client you use. Most clients have a hook for intercepting calls before they hit promise callbacks. You would set this up when you setup the client and not on a call-by-call basis.
Here is some docs for axios, for example
If the service returns
200 OK
,fetch
won’t know an error occurred, so it won’t throw an error for thecatch
block to handle. If the API successfully returns anything, even an error object, it’s up to the client to examine the returned data and interpret it appropriately.