When using Axios for HTTP requests, if the request fails, Axios generates an error object. We can retrieve the HTTP status code by capturing this error object. When a request fails, the Axios error object (typically named error) contains a response property, which is an object holding HTTP response information. The response object further includes a status property, which represents the HTTP status code.
The following is a basic method to capture Axios errors and retrieve the status code:
javascriptaxios.get('/some-endpoint') .then(response => { // Request successful: handle response data console.log(response.data); }) .catch(error => { // Request failed: handle error if (error.response) { // Server returned an error code and message console.log("Error Status Code:", error.response.status); console.log("Error Response Data:", error.response.data); console.log("Error Response Headers:", error.response.headers); } else if (error.request) { // Request was sent, but no response received console.log("No response received:", error.request); } else { // An error occurred during request setup console.log("Error Message:", error.message); } // Additional error handling });
In this code snippet, we first attempt to make a GET request to a specific endpoint. If the request succeeds, we process the response in the .then() block. If the request fails, Axios executes the code in the .catch() block. Within the .catch() block, we first verify if error.response exists. If it does, we can read the status code from it, which typically indicates that the server processed the request but returned an error status code. If error.response is absent, we check error.request to determine subsequent actions. If error.request also does not exist, the issue likely occurred during request setup, such as an invalid URL.
For instance, if the backend service returns a 404 status code indicating the requested resource was not found, we can observe this status code in error.response.status. Similarly, if a 500 status code is returned, signifying a server internal error, we can retrieve this information via error.response.status and implement appropriate error handling measures.