Handling Axios error in React
I have a React component that calls a function getAllPeople:
componentDidMount() {
getAllPeople().then(response => {
this.setState(() => ({ people: response.data }));
});
}
getAllPeople is in my api module:
export function getAllPeople() {
return axios
.get("/api/getAllPeople")
.then(response => {
return response.data;
})
.catch(error => {
return error;
});
}
I think this is a very basic question, but assuming I want to handle the error in my root component (in my componentDidMount method), not in the api function, how does this root component know whether or not I the axios call returns an error? I.e. what is the best way to handle errors coming from an axios promise?The getAllPeople function already returns the data or error message from your axios call. So, in componentDidMount, you need to check the return value of your call to getAllPeople to decide whether it was an error or valid data that was returned. componentDidMount() { getAllPeople().then(response => { if(response!=error) //error is the error object you can get from the axios call this.setState(() => ({ people: response})); else { // your error handling goes here } }); } If you want to return a promise from your api, you should not resolve the promise returned by your axios call in the api. Instead you can do the following: export function getAllPeople() { return axios.get("/api/getAllPeople"); } Then you can resolve in componentDidMount. componentDidMount() { getAllPeople() .then(response => { this.setState(() => ({ people: response.data})); }) .catch(error => { // your error handling goes here } }
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/99dfd2bd6724e701259c2cb2e72e45c5d2028b1ed0c14b2c0be958437eacd257