Home > Software design >  How to catch axios api call error 401 in reactjs?
How to catch axios api call error 401 in reactjs?

Time:05-18

I am using axios to make apis calls in react. If there is no token provided or token got expired server sends the 401 status. I want to check that status on reactjs side.

But if i check err object in catch the status field is null.

Here is the code

try {
   MyService.getIntet(reqBody);
  } catch (err) {
    handleUnAuthorizedResponse(err);
  }

error returns this

Service function:

import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
  headers: {
    "Content-Type": "application/json"
  },
};
return axios
  .post(url, reqBody, options)
  .then((res) => res.data)
}

How to handle 401 error ?

CodePudding user response:

You need to wrap the trycatch in async function and await MyService.getIntet(reqBody) to catch the error. The status code is in err.response.status.

You could also just MyService.getIntet(reqBody).catch(handleUnAuthorizedResponse) if you don't want to wrap it in async function.

CodePudding user response:

You can use .catch chaining function after .then to catch all errors. Error object will contain a response object which will contain actual response received by API response with all meta information. But make sure to put a condition while accessing this object as errors caught from the then block will not have response key.

import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
  headers: {
    "Content-Type": "application/json"
  },
};
return axios
  .post(url, reqBody, options)
  .then((res) => res.data)
  .catch(error => console.log(error.response.status))
}
  • Related