Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch 401 error using fetch method of javascript

Tags:

javascript

api

I need to catch error 401 Code of response so that I can retry after getting a new token from token endpoint. I am using fetch method get data from API.

   const request: Request = new Request(url.toString(), {         headers: this.defaultRequestHeaders,         method: "get",         mode: "cors"     });     const headers: Headers = new Headers({         "Accept": "application/json",         "Content-Type": "application/json"     });     fetch(request)         .then(function(response)          {           ///Logic code          })         .catch(function(error)         {           ///if status code 401. Need help here         }); 
like image 772
Vikrant Singh Avatar asked Apr 18 '18 14:04

Vikrant Singh


People also ask

How do I fix 401 unauthorized error fetch?

401 error on fetch() Based on the error message that you received it looks like you need to authenticate into the service. So, you need to look at the documentation for the service and see what type of credentials you need to pass in with your request.

Can we use fetch in JavaScript?

JavaScript | fetch() Method. The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

What errors does fetch catch?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.


2 Answers

You can check the status and if it's not 200 (ok) throw an error

 fetch("some-url")     .then(function(response)      {       if(response.status!==200)        {           throw new Error(response.status)        }      })     .catch(function(error)     {       ///if status code 401...     }); 
like image 85
Israel kusayev Avatar answered Sep 28 '22 02:09

Israel kusayev


Because 401 is actually a valid response to a request to a server, it will execute your valid response regardless. Only if security issues occur, or if the server is unresponsive or simply not available will the catch clause be used. Just think of it like trying to talk to somebody. Even if they say "I am currently not available" or "I don't have that information", your conversation was still successful. Only if a security guy comes in between you and stops you from talking to the recipient, or if the recipient is dead, will there be an actual failure in conversation and will you need to respond to that using a catch.

Just separate out your error handling code so you can handle it in instances that the request was successful, but does not have the desired outcome, as well as when an actual error is being thrown:

function catchError( error ){      console.log( error );  }  request.then(response => {      if( !response.ok ){          catchError( response );      } else {          ... Act on a successful response here ...      }  }).catch( catchError ); 

I am using the response.ok suggested by @Noface in the comments, as it makes sense, but you could check for only the response.status === 401 if you want to.

like image 42
somethinghere Avatar answered Sep 28 '22 02:09

somethinghere