How to catch 401 error using fetch method of javascript

北战南征 提交于 2021-01-20 23:39:57

问题


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
        });

回答1:


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...
    });



回答2:


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.




回答3:


You can try this

fetch(request)
  .then(function(response) {
    if (response.status === 401) {
      // do what you need to do here
    }
  })
  .catch(function(error) {
        console.log('DO WHAT YOU WANT')
});



回答4:


You can check the status of the response in then:

fetch(request)
  .then(function(response) {
    if (response.status === 401) {
      // do what you need to do here
    }
  })
  .catch(function(error) {});



回答5:


(function () {
var originalFetch = fetch;
fetch = function() {
    return originalFetch.apply(this, arguments).then(function(data) {
        someFunctionToDoSomething();
        return data;
    });
};})();

source Can one use the Fetch API as a Request Interceptor?




回答6:


When you want to...

catch (error) {
  console.dir(error) // error.response contains your response
}



回答7:


fetch(url,{
            method: 'GET',
            headers,
            body: JSON.stringify(aData)
        }).then(response => {
            if(response.ok){
                return response.json();
            }

            return Promise.reject(response);
        }).catch(e => {
            if(e.status === 401){
                // here you are able to do what you need
                // refresh token ..., logout the user ...
                console.log(e);
            }

            return Promise.reject(e.json());
        });


来源:https://stackoverflow.com/questions/49902417/how-to-catch-401-error-using-fetch-method-of-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!