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));
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
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With