How to catch 401 error using fetch method of javascript

前端 未结 5 875
野性不改
野性不改 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:57

    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.

提交回复
热议问题