Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to handle 404 error in fetch?

When I call the request function passing a number which I know I will get a 404 error, I cant handle it, I dont know how to do it.

async request(number) {
    var request = "https://reqres.in/api/users/"+number;

    fetch(request, {method: "GET"})
    .then((response) => {
      return response.json(); 
    })
    .then((responseJson) => {
      this.setState({nombre:responseJson.data.first_name})
    })
    .catch((error) => {
      this.setState({nombre:error})
    }).done();
}

Full code: https://codeshare.io/5wWo9p

like image 660
Fran Avatar asked Dec 23 '22 20:12

Fran


2 Answers

you can check for response status to handle 404 or other errors use below example:

fetch('your url goes here')
  .then(response => {
    if (response.ok) {
      return response.json()
    } else if(response.status === 404) {
      return Promise.reject('error 404')
    } else {
      return Promise.reject('some other error: ' + response.status)
    }
  })
  .then(data => console.log('data is', data))
  .catch(error => console.log('error is', error));
like image 65
Farhad Avatar answered Dec 28 '22 23:12

Farhad


Error 404 is normally interpreted as (kind of) success and don't go into catch section. But you can send it into catch by throwing error … like:

fetch(
    request
).then( ( /** @type {Response} */ response ) =>
{
    if ( response.ok ) {
        return response.json();
    } else {
        throw 'some error text';
    }
} ).then( ( responseJson ) =>
{
    // to something with success response
} ).catch( ( error ) =>
{
    // every possible kind of error even 404
} );
like image 33
iiic Avatar answered Dec 28 '22 22:12

iiic