If I have a fetch like this:
fetch('https://jsonplaceholder.typicode.com/comments/1') // returns a promise
.then(response => response.json()) // returns a promise aswell
.then(data => console.log(data))
how would I catch a 404 error, if I f.e. go to comments/522 (which does not exist)?
I tried it by adding a catch statement at the end:
fetch('https://jsonplaceholder.typicode.com/comments/522') // returns a promise
.then(response => response.json()) // returns a promise aswell
.then(data => console.log(data))
.catch((error) => {
console.log("Error Msg!");
})
However that does not seem to catch that error.
I also tried according to this post (javascript fetch does not catch 404 error) to check for the response status, but while I’m able to do that, the second ‘.then’ method did not run:
fetch('https://jsonplaceholder.typicode.com/comments/522')
.then(response => {
if (response.status == '404') {
console.log(response.status);
} else {
response.json();
}
} )
.then(data => console.log(data))
>Solution :
In order to catch a 404 error in a fetch request, you can add a .catch method to the end of the fetch promise chain. Inside the .catch method, you can check the response.status property to see if it equals 404. Here’s an example:
fetch('https://jsonplaceholder.typicode.com/comments/522')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.response.status === 404) {
console.log('404 error: resource not found')
}
});
In your code, you are trying to check the response.status inside the first .then method, but this will not work because response.json() returns a promise. Instead, you need to return the promise from response.json() and add a .catch method after it to handle the error.
fetch('https://jsonplaceholder.typicode.com/comments/522')
.then(response => {
if (response.status === 404) {
console.log('404 error: resource not found')
} else {
return response.json();
}
})
.then(data => console.log(data))
.catch(error => console.log(error));
In the code above, if the response.status is 404, we log an error message and the code in the second .then method is not executed. Otherwise, the response.json() promise is returned and handled in the second .then method. The .catch method at the end is used to catch any errors that may occur in the response.json() promise.