Source:  Twitter logo

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

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));
12 users liked answer #0dislike answer #012
Farhad profile pic
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
} );
1 users liked answer #1dislike answer #11
iiic profile pic
iiic

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).