Reputation: 2823
react newbie here. I was using the react fetch api and came across an issue when trying to throw a custom error. I have a rest api endpoint running on localhost:8080. I have since turned off the process (mimicking a down service) I want to throw a more descriptive error rather than the standard "Failed to Fetch" error. It seems the code is rejecting my error above and using the default fetch error. Is there a way to override this?
fetchData() {
fetch('http://localhost:8080/locales/all')
.then(function(response) {
if (response.ok) {
return response.json();
}
throw Error('Oops, looks like the service is down :-(');
})
.then(parsedJSON => {
this.setState({
locales: parsedJSON.content,
isLoading:false
});
}).catch(error => {
this.setState({
error: error.message,
isLoading:false
});
console.log(error.message); // results in Failed to fetch
});
Upvotes: 0
Views: 328
Reputation: 370639
The issue is that the initial fetch
call may resolve with a Response
object, but if the fetch
fails completely, it will not resolve at all, and will proceed directly to the catch
. This will be clear if you put this in your code:
fetch('http://localhost:8080/locales/all')
.then(function(response) {
console.log('got a response');
When you don't see got a response
, you won't be able to throw
the custom error message inside the .then
.
function fetchData() {
fetch('http://localhost:8080/locales/all')
.then(function(response) {
console.log('got a response');
if (response.ok) {
return response.json();
}
throw new Error('Oops, looks like the service is down :-(');
}).catch(error => {
console.log(error.message);
});
}
fetchData();
Rather, you might change the error message inside the catch
itself:
}).catch(error => {
if (error.message === 'Failed to fetch') {
// change the message, or handle as needed:
error.message = 'Oops, looks like the service is down :-(';
}
function fetchData() {
fetch('http://localhost:8080/locales/all')
.then(function(response) {
console.log('got a response');
if (response.ok) {
return response.json();
}
throw new Error('Oops, looks like the service is down :-(');
}).catch(error => {
if (error.message === 'Failed to fetch') {
error.message = 'Oops, looks like the service is down :-(';
}
console.log(error.message);
});
}
fetchData();
Upvotes: 1