I really liked @tjvantoll article Handling Failed HTTP Responses With fetch(). The one thing I found annoying with it, though, is that response.statusText
always returns the generic error message associated with the error code. Most APIs, however, will generally return some kind of useful, more human friendly message in the body.
Here's a modification that will capture this message. The key is that rather than throwing an error, you just throw the response and then process it in the catch
block to extract the message in the body:
fetch("/api/foo")
.then( response => {
if (!response.ok) { throw response }
return response.json() //we only get here if there is no error
})
.then( json => {
this.props.dispatch(doSomethingWithResult(json))
})
.catch( err => {
err.text().then( errorMessage => {
this.props.dispatch(displayTheError(errorMessage))
})
})
Frankly, I'm horrified that JavaScript let's you throw some random value, rather than an error, but hey, when in Rome...
Nice post, tnx :)
If you want to use message from API as error message.
In my case:
Api will return 400 in case of invalid data sent in request. Response body will contain: {"message":"Some nasty error message!"}. I want to use this message as error. But there is a problem if you want to reject promise. Because Promise.reject will reject immediately, and will not wait for resolving of result.json() for example.
Here is my take if you want to wait for result.json() and then use resulted json data as error.
Hope it helps :)