How to catch 401 error using fetch method of javascript

前端 未结 5 852
野性不改
野性不改 2021-02-12 10:09

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         


        
5条回答
  •  感情败类
    2021-02-12 10:45

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

提交回复
热议问题