0

I'm using Cross fetch for my ReactJS API calls

Is there a way to capture 400 401 & 403 in fetch response.

Here is sample code of using fetch

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
     body: 'bar',
     userId: 1
   }),
   headers: {
     "Content-type": "application/json; charset=UTF-8"
   }
})
.then(response => response.json())
.then(json => console.log(json))
1
  • Try to add in the first then : .then(response => { if(response.status===400) { console.log('status 400'); } return response.json() } Commented Jul 13, 2018 at 14:24

1 Answer 1

1

You can check the status code in the callback given to the first then:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
})
.then(response => {
  if ([400, 401, 403].includes(response.status)) {
    throw new Error('Response status was 400, 401, or 403!');
  }

  return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))
Sign up to request clarification or add additional context in comments.

6 Comments

It did not work as expected. It didn't show the msg. got 400 error on console not by code.
@Selvin It works when I try it. Are you sure you are testing the correct code? I updated the answer with a way of throwing an error, and loggin it in the catch instead.
this should work, it's used exactly the same way as the first example of the readme. If it does not do what you want it's either because you're unclear with what you want or you are doing something elsewhere in your code that breaks this example
tried with updated code getting error like Network request failed on catch
@Selvin Then it's something else that makes the request not succeed. The then callback is never run.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.