Error Handling With Axios
An HTTP request can succeed or fail. Errors can occur and it is the developer’s responsibility to handle the errors for a better user experience. Errors can occur due to a variety of reasons like server errors, authentication errors, missing parameters and requesting resources that may not exist. Axios, by default, rejects any response with a status code that falls outside the successful 2xx range. But this feature can be modified to specify what range of HTTP codes should throw an error using the validateStatus config option. Following is an example depicting this:
axios({
baseURL: "endpoint",
url: "/todos/1",
method: "get",
validateStatus: status => status <= 500,
})
.then((response) => {
console.log(response.data);
})
.catch(error => {
console.log(error)
})
the error object that Axios passes to the .catch block has several properties like name, message, code, status, stack and config and can be accessed like this: error.name. In addition these properties, if the request was made and the server responded with a status code that falls outside the 2xx range, the error object will also have the error.response object. On the other hand, if the request was made but no response was received, the error object will have an error.request object.
axios.post("/login", credentials)
.then(response => {
console.log(response);
})
.catch(error => {
if (error.response) {
//response status is an error code
console.log(error.response.status);
}
else if (error.request) {
//response not received though the request was sent
console.log(error.request);
}
else {
//an error occurred when setting up the request
console.log(error.message);
}
})
How To Use Axios NPM to Generate HTTP Requests ?
In this article, we are going to learn about Axios and HTTP requests and using Axios to generate HTTP requests. Axios is a promise-based HTTP library that is used by developers to make requests to their APIs or third-party API endpoints to fetch data. It is a popular JavaScript library used for making HTTP requests from web browsers and NodeJS applications. It provides a simple and intuitive API for performing asynchronous operations like fetching data from APIs, posting form data, and more.
Table of Content
- HTTP Requests
- Axios
- How does Axios work?
- Installing Axios NPM for Your Project
- Creating an Axios Instance With Default Settings
- Performing GET Requests With Axios
- Performing POST Requests With Axios
- Sending Data with POST Requests
- Handling Response Data From POST Requests
- Shorthand Methods for Axios HTTP Requests
- Error Handling With Axios
- Conclusion
Contact Us