Question
Answer and Explanation
When making API calls with Axios in Node.js, proper error handling is crucial. Here's how you can detect and manage errors:
1. Using Try-Catch Blocks:
- The most common method for catching errors in asynchronous operations is by wrapping the Axios request within a try...catch
block. Any error thrown during the request process (network errors, server errors, etc.) will be caught in the catch
block.
2. Checking for Response Status Codes:
- Axios automatically throws an error for response status codes outside the 2xx range. However, to handle errors based on different status codes, you'll need to examine the response within the catch
block. The response
object has a status property which holds the HTTP status code.
3. Example Code with Error Handling:
const axios = require('axios');
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Data:', response.data);
} catch (error) {
if (error.response) {
console.error('Server responded with an error:', error.response.status, error.response.data);
} else if (error.request) {
console.error('Request was made but no response received:', error.request);
} else {
console.error('Error during setup or processing:', error.message);
}
}
}
fetchData();
4. Explanation of the Error Object:
- When an error occurs during an Axios request, the error object provides key properties:
- error.response
: This is available when the server responds with an error status code (4xx or 5xx). It contains:
error.response.status
: The HTTP status code of the response.error.response.data
: The response body, which might contain additional error details.error.response.headers
: The headers of the response. - error.request
: This is available when the request was made, but no response was received, often due to network errors.
- error.message
: This provides details if there was a general error during the request setup or processing.
5. Custom Error Handling:
- You can implement custom error handling logic based on the status code or error type. For example, you can retry requests, log specific errors, or display user-friendly messages.
By implementing these error handling techniques, you ensure robustness when making API calls using Axios in your Node.js applications.