'How to catch axios api call error 401 in reactjs?
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);
}
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 ?
Solution 1:[1]
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.
Solution 2:[2]
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))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Veselin Ivanov |
| Solution 2 | Rajan Vasani |
