如何使用JavaScript的获取方法捕获401错误

Vik*_*ngh 7 javascript api

我需要捕获错误401响应代码,以便从令牌端点获取新令牌后可以重试。我正在使用fetch方法从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
        });
Run Code Online (Sandbox Code Playgroud)

som*_*ere 10

因为401实际上是对服务器请求的有效响应,所以无论如何它都会执行您的有效响应。只有在出现安全问题,或者服务器无响应或根本不可用时,catch才会使用该子句。把它想象成试图与某人交谈。即使他们说“我目前不可用”或“我没有该信息”,您的对话仍然是成功的。只有当保安人员挡在您之间并阻止您与接收者交谈时,或者接收者已死时,才会出现真正的对话失败并且您需要使用catch.

只需将您的错误处理代码分开,以便您可以在请求成功但没有预期结果的情况下处理它,以及在抛出实际错误时:

function catchError( error ){

    console.log( error );

}

request.then(response => {

    if( !response.ok ){

        catchError( response );

    } else {

        ... Act on a successful response here ...

    }

}).catch( catchError );
Run Code Online (Sandbox Code Playgroud)

response.ok在评论中使用@Noface 建议的,因为它是有道理的,但您可以仅检查response.status === 401是否需要。


Sal*_*eem 8

你可以试试这个

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')
});
Run Code Online (Sandbox Code Playgroud)


Isr*_*yev 6

您可以检查状态,如果不是200(确定),则会抛出错误

 fetch("some-url")
    .then(function(response)
     {
      if(response.status!==200)
       {
          throw new Error(response.status)
       }
     })
    .catch(function(error)
    {
      ///if status code 401...
    });
Run Code Online (Sandbox Code Playgroud)

  • 如果 HTTP 响应的状态为 401,则不会调用“catch”方法的回调函数;相反,将调用“then”方法的回调函数,并返回“response.status === 401”。 (2认同)

Dar*_*rio 5

您可以在以下位置检查status响应then

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


vin*_*ess 5

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());
        });
Run Code Online (Sandbox Code Playgroud)