Explain Codes LogoExplain Codes Logo

How can I get the status code from an HTTP error in Axios?

javascript
error-handling
axios
javascript-patterns
Alex KataevbyAlex Kataev·Oct 9, 2024
TLDR

To retrieve HTTP error statuses in Axios, make use of error.response.status situated within the .catch() block:

axios.get('your/api/endpoint') .catch(error => console.log(error.response?.status));

This snippet can be the difference between an unhandled error and a well-managed application.

Clearing the fog: Error handling made easy

When it comes to HTTP requests, throwing a "catch-all" net isn't sufficient. We need to categorize, diagnose and act upon the errors. Let's structure the error inside .catch() for better clarity:

axios.get('your/api/endpoint') .then(response => /* hallelujah success! */) .catch(error => { if (error.response) { // The server was woken up but it responded with a bad mood (status code outside of 2xx) console.log('Status:', error.response.status); // "Hey, what's the server's mood?" console.log('Body:', error.response.data); // "I wonder what the server says." console.log('Headers:', error.response.headers); // "Any secret message from server?" } else if (error.request) { // The request was made but no response was received, our server might be fast asleep. console.log(error.request); } else { // The server said, "Your request doesn't make sense.", blame goes to us poor human developers. console.log('Error', error.message); // "Yikes, what did I do wrong?" } console.log(error.config); // "Let's peek into the request configuration." });

This organized error handling strategy assists in differentiating Axios error types for a complete understanding and an improved debugging experience.

Serving a cocktail of JavaScript patterns

Digging deeper in the error treasure

Beyond the surface level, error.response.data houses the explanation given by the server. It's a gold mine for debugging.

Beholding whole unfolded error canvas

Flipping the error object inside out via JSON.stringify(error) would help to get a complete look of the error:

.catch(error => console.log(JSON.stringify(error, null, 2)));

TypeScript magic in axios error handling

Utilizing TypeScript for AxiosResponse and AxiosError stands as an insurance policy against runtime errors, and serves top-notch autocomplete features.

Edge-cutting error handlers

Sometimes, we want to customize how Axios defines an error. In comes validateStatus function in config, defining our terms and conditions to the server:

axios.get('your/api/endpoint', { validateStatus: function (status) { return status < 500; // Any crime below 500 is pardonable } })

Deciphering status codes

Smartly branch out various HTTP status codes using if-else or switch within the catch block for granular error handling.

Error object: Unleashing the beast

To extract the valuable information swiftly, destructure status, data, and headers from the error object, showcasing JavaScript's destructuring potential.

Taking error responses seriously

More than the status code, it's important to understand the server's response. Debug effectively by inspectively error.response.data.

Not just status, headers matter too

Headers can contain useful information like rate-limit etc. error.response.headers lets you sneak into that detail.

Spreading the error, not literally

Instead of battling with the whole error object, spread it and conquer part-by-part:

.catch(error => { const errorDetails = { ...error.response }; console.log('Error Deconstructed:', errorDetails); // "Let's see what's inside!" });

Marrying TypeScript with Axios

With TypeScript and Axios, you can define the expected structure of response.data and enjoy the comfort of type-checking and autocomplete.

Problem patterns

Find patterns in error responses and develop robust error handling that separates operational errors (like "404-Not Found", "503-Service Unavailable") from programmer errors (ahem... those bugs).