Fran
Fran

Reputation: 203

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

Upvotes: 9

Views: 21008

Answers (2)

iiic
iiic

Reputation: 1362

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
} );

Upvotes: 1

Farhad
Farhad

Reputation: 2003

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));

Upvotes: 19

Related Questions