0

enter image description here

enter image description here

So here my code works fine it verifies the token and sends the client data but What I want is when user is not verified it will throw an error and I will catch the error and automatically make the user signout. but My async function could not catch the 403 error. The error shows directly instead. Is there any Syntax mistake or I am doing anything wrong ?

TRO J1N
  • 19
  • 4

1 Answers1

1

This'll be because in fetch (unlike in axios), a 403 does not throw an error as it's considered a successful request. The request completed, and returned data, it just happened to be HTTP Status code 403.

You need to manually check response.ok (boolean). A simple thing you can try is to throw an error, then your catch will be triggered as you expected.

const response = await fetch(......)
if (!response.ok) {
 // something has gone wrong
 // you could throw an error here..
 throw new Error(response.statusText);
}
Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
  • 3
    A small suggestion would be to use `if (!response.ok) { ... }` to make it a little neater. I think you meant `const response = await fetch(...);` on the first line? – Richard Barrell May 05 '22 at 11:13