Handling API errors
Overview
API error handling ensures that network errors, server errors, or invalid responses are handled gracefully, providing a better user experience.
Handling API Errors with Axios
Step 1: Create an Axios Instance
Create an api.js
file:
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
timeout: 5000,
});
// Add a request interceptor
api.interceptors.request.use(
(config) => {
// Add custom headers or authentication tokens
config.headers["Authorization"] = `Bearer ${localStorage.getItem("token")}`;
return config;
},
(error) => Promise.reject(error)
);
// Add a response interceptor
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response) {
// Server errors
console.error("Server Error:", error.response.status);
alert(`Error: ${error.response.data.message || "An error occurred."}`);
} else if (error.request) {
// Network errors
console.error("Network Error:", error.message);
alert("Network error. Please check your internet connection.");
} else {
console.error("Unexpected Error:", error.message);
}
return Promise.reject(error);
}
);
export default api;
Step 2: Use the Axios Instance
In your API calls, use the configured Axios instance:
import api from "./api";
const fetchData = async () => {
try {
const response = await api.get("/data");
console.log("Data:", response.data);
} catch (error) {
console.error("API Error:", error);
}
};
fetchData();
Best Practices for API Error Handling
- Provide meaningful error messages to users.
- Retry failed requests if applicable.
- Log errors for debugging and analytics.
- Implement fallback mechanisms for critical failures.
With these strategies, you can effectively handle both global and API-specific errors, ensuring a robust and user-friendly application.