1

My axios post request is not returning the value returned by the API in a non success 401 scenario. It works fine when its a success scenario.

My reset Password API returns the status code, and a message for every call. when I use post man to test its output for resetting a password, giving incorrect current password, I get

Postman Output:

 statusCode: 401,
            headers: {
               .......
               ........
            },
body: "{"code":"NotAuthorizedException","name":"NotAuthorizedException","message":"Incorrect username or password."}" <--- This is the body output

But in my axios post, it goes to the catch block:

await Axios.post(resetAPIUrl, resetParams, config).then(value=> {
                    console.log(`Returned data ----> ${JSON.stringify(value)}`);
                    resolve(value);
                }).catch(error=>{
                    console.log(`Failing--->${error}`)
                    reject(error)
                });

this is the error that I am getting in the catch block of Axios post:

Error: Request failed with status code 401

The error reason is correct. But why isn it going into catch block? Its a successful completion of the process. Calling the API directly from post man gives me the correct output structure.

Gaurav Thantry
  • 103
  • 1
  • 13
  • The title mentions it enters the catch block but your last sentence said it isn't going into the catch block. Which is actually happening here? – Halmon Oct 30 '20 at 23:29
  • Oopps. My mistake. It is going into the catch block. I don't want it to go the catch blaock, and give me the API response. – Gaurav Thantry Oct 30 '20 at 23:32
  • 3
    Because axios by default only considers 2xx status codes to be successes. – Bergi Oct 30 '20 at 23:33
  • 1
    Btw, avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Oct 30 '20 at 23:34
  • Oh didn't know that. Is there any way to get the exact API response in the catch block? The API resturns the status code, headers, and body even for all status codes. – Gaurav Thantry Oct 30 '20 at 23:35
  • 2
    If you want to handle 401s, in the error block you can add an `if (status === 401)` and work from there – Halmon Oct 30 '20 at 23:36
  • 1
    @Bergi I would say it's more an issue of mixing `async/await` with Promise chaining than it is starting/constructing a Promise... `axios` handles that. OP could clearly just use a `try/catch` and await the response. That post is over 6 years old (!) and the landscape has shifted. – Drew Reese Oct 30 '20 at 23:48
  • 2
    @DrewReese Mixing `await` with `then` might also be an issue, both those `resolve(value)` and `reject(error)` calls in the callbacks look suspiciously like the promise constructor antipattern. Yes, it's old, but still a mistake. – Bergi Oct 30 '20 at 23:52
  • @Bergi Right, ok, I see now that `resolve`/`reject` are from another scope not included in the snippet. – Drew Reese Oct 30 '20 at 23:59
  • 1
    Trying to use interceptors to handle 401. Didn't know that existed. – Gaurav Thantry Oct 31 '20 at 00:06
  • Hi @Bergi, yes the resolve/reject are for the promise which is for a different scope. The above snippets are in a reset function, that returns a promise – Gaurav Thantry Oct 31 '20 at 00:08

1 Answers1

1

Interceptor was the answer. Since Axios doesn't consider any response other than 200 as the success scenario, interceptors can be used to capture the other responses:

{     
                Axios.interceptors.request.use(req=>{
                   console.log(`This is the request ---> ${req.method} ${req.url}`)
                   return req;
                })
                Axios.interceptors.response.use(res => {
                    console.log(`res status ---> ${res.status}`)
                    resolve(res)
                    return res;
                }, (error)=>{
                    console.log(`This is the error status ---> ${error.response.status}`)
                    if(error.response.status === 401){
                       resolve(error.response);
                    }
                })
                await Axios.post(resetAPIUrl, resetParams, config);
Gaurav Thantry
  • 103
  • 1
  • 13