Introduction
Axios is a JavaScript library that uses the Promise API to create HTTP requests with http
in Node.js runtime or XMLHttpRequests
in the browser. Because these requests are promises, they work with the newer async/await syntax, as well as .then()
functions for promise chaining and the .catch()
mechanism for error handling.
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
// Handle error
console.log(err);
}
In this article, we will see how to handle errors with Axios, as this is very important when making any HTTP calls knowing fully well that there are times when the service you're calling might not be available or return other unexpected errors. We'll show the
.then()
/.catch()
method, but primarily use the async/await syntax.
Then and Catch
Promises can be handled in two ways using modern JS - the async/await syntax, which was shown above, as well as .then()
and .catch()
methods. Note that both of these methods can produce the same functionality, but async/await is typically regarded as being easier to work with and requires less boilerplate code in longer promise chains.
Here is how you'd achieve the same thing, but using the then/catch method:
axios.get('/my-api-route')
.then(res => {
// Work with the response...
}).catch(err => {
// Handle error
console.log(err);
});
Both the res
and err
objects are the same as with the async/await syntax.
Handling Errors
In this section, we will look at two primary categories of problems, as well as other issues that we may encounter and how to manage them using Axios. It is critical that you understand that this applies to all types of HTTP queries handled by Axios, including GET
, POST
, PATCH
, and so on.
Here you can see the syntax for the three aspects - this will capture the error; it is crucial to note that this error carries a large error object with a lot of information:
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
}
}
The differences in the error object, highlighted above in the catch
code, indicate where the request encountered the issue. We'll look deeper into this in the following sections.
error.response
This is the type of mistake we are most familiar with, and it is much easier to deal with. Many sites display a 404 Not Found page/error message or various response codes based on what the API provides; this is often handled via the response.
If your error object has a response property, it signifies your server returned a 4xx/5xx error. This will assist you choose what sort of message to return to users; the message you'll want to provide for 4xx may differ from that for 5xx, and if your backend isn't returning anything at all.
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
}
}
error.request
This error is most commonly caused by a bad/spotty network, a hanging backend that does not respond instantly to each request, unauthorized or cross-domain requests, and lastly if the backend API returns an error.
Note: This occurs when the browser was able to initiate a request but did not receive a valid answer for any reason.
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
console.log(err.request);
} else {
// Anything else
}
}
Earlier we mentioned that the underlying request Axios uses depends on the environment in which it's being run. This is also the case for the err.request
object. Here the err.request
object is an instance of XMLHttpRequest
when being executed in the browser, whereas it's an instance of http.ClientRequest
when being used in Node.js.
Other Errors
It's possible that the error object does not have either a response
or request
object attached to it. In this case it is implied that there was an issue in setting up the request, which eventually triggered an error.
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
console.log('Error', err.message);
}
}
For example, this could be the case if you omit the URL parameter from the .get()
call, and thus no request was ever made.
Conclusion
In this short article, we looked at how we may handle various sorts of failures and errors in Axios. This is also important for giving the correct message to your application/website visitors, rather than always returning a generic error message, sending a 404, or indicating network problems.