- Spec files
npm-axios
Describes: pkg:npm/axios@1.11.x
- Description
- Promise based HTTP client for the browser and node.js
- Author
- tessl
- Last updated
error-handling.md docs/
1# Error Handling23Structured error handling with detailed error information, error codes, and type checking utilities for robust application error management.45## Capabilities67### AxiosError Class89Main error class extending native Error with detailed context about failed requests.1011```javascript { .api }12/**13* Axios-specific error with request/response context14*/15class AxiosError<T = unknown, D = any> extends Error {16constructor(17message?: string,18code?: string,19config?: InternalAxiosRequestConfig<D>,20request?: any,21response?: AxiosResponse<T, D>22);2324/** Request configuration that caused the error */25config?: InternalAxiosRequestConfig<D>;26/** Error code string */27code?: string;28/** Request object (XMLHttpRequest, IncomingMessage, etc.) */29request?: any;30/** Response object if server responded */31response?: AxiosResponse<T, D>;32/** Always true for AxiosError instances */33isAxiosError: boolean;34/** HTTP status code if available */35status?: number;36/** Underlying error cause */37cause?: Error;3839/** Serialize error to JSON object */40toJSON(): object;41}42```4344**Usage Examples:**4546```javascript47import axios from "axios";4849try {50const response = await axios.get("https://api.example.com/users");51} catch (error) {52if (axios.isAxiosError(error)) {53console.log("Error message:", error.message);54console.log("Error code:", error.code);55console.log("Request URL:", error.config?.url);56console.log("HTTP status:", error.response?.status);57console.log("Response data:", error.response?.data);5859// Serialize for logging60console.log("Full error:", error.toJSON());61}62}63```6465### Error Code Constants6667Predefined error codes for common failure scenarios.6869```javascript { .api }70// Network and connection errors71static readonly ERR_NETWORK = "ERR_NETWORK";72static readonly ECONNABORTED = "ECONNABORTED";73static readonly ETIMEDOUT = "ETIMEDOUT";7475// Request/Response errors76static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";77static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";7879// Configuration errors80static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";81static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";8283// Feature/Support errors84static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";85static readonly ERR_DEPRECATED = "ERR_DEPRECATED";8687// URL errors88static readonly ERR_INVALID_URL = "ERR_INVALID_URL";8990// Cancellation errors91static readonly ERR_CANCELED = "ERR_CANCELED";9293// Redirect errors94static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";95```9697**Usage Examples:**9899```javascript100try {101const response = await axios.get(url, { timeout: 5000 });102} catch (error) {103if (axios.isAxiosError(error)) {104switch (error.code) {105case axios.AxiosError.ETIMEDOUT:106console.log("Request timed out");107break;108case axios.AxiosError.ERR_NETWORK:109console.log("Network error occurred");110break;111case axios.AxiosError.ERR_BAD_REQUEST:112console.log("Bad request configuration");113break;114case axios.AxiosError.ERR_CANCELED:115console.log("Request was canceled");116break;117default:118console.log("Unknown error:", error.code);119}120}121}122```123124### Error Factory Method125126Create AxiosError instances from existing errors.127128```javascript { .api }129/**130* Create AxiosError from existing error131* @param error - Original error object132* @param code - Error code to assign133* @param config - Request configuration134* @param request - Request object135* @param response - Response object136* @param customProps - Additional properties137* @returns New AxiosError instance138*/139static AxiosError.from<T = unknown, D = any>(140error: Error | unknown,141code?: string,142config?: InternalAxiosRequestConfig<D>,143request?: any,144response?: AxiosResponse<T, D>,145customProps?: object146): AxiosError<T, D>;147```148149**Usage Examples:**150151```javascript152// Convert generic error to AxiosError153try {154// Some operation that might throw155throw new Error("Something went wrong");156} catch (originalError) {157const axiosError = axios.AxiosError.from(158originalError,159"CUSTOM_ERROR",160config,161request,162response,163{ customProperty: "additional context" }164);165166throw axiosError;167}168```169170### CanceledError Class171172Specific error type for canceled requests.173174```javascript { .api }175/**176* Error thrown when request is canceled177*/178class CanceledError<T> extends AxiosError<T> {179constructor(message?: string, config?: InternalAxiosRequestConfig, request?: any);180}181182// Legacy alias for backward compatibility183const Cancel = CanceledError;184```185186### Error Type Checking187188Utility functions to identify different types of errors.189190```javascript { .api }191/**192* Check if error is an AxiosError instance193* @param payload - Value to check194* @returns True if payload is AxiosError195*/196axios.isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;197198/**199* Check if error is due to request cancellation200* @param value - Value to check201* @returns True if value represents cancellation202*/203axios.isCancel(value: any): value is Cancel;204```205206**Usage Examples:**207208```javascript209try {210const response = await axios.get(url);211} catch (error) {212if (axios.isCancel(error)) {213console.log("Request was canceled:", error.message);214return; // Handle cancellation gracefully215}216217if (axios.isAxiosError(error)) {218// Handle different HTTP status codes219if (error.response) {220switch (error.response.status) {221case 400:222console.log("Bad request:", error.response.data);223break;224case 401:225console.log("Unauthorized - redirect to login");226window.location.href = "/login";227break;228case 403:229console.log("Forbidden - insufficient permissions");230break;231case 404:232console.log("Resource not found");233break;234case 429:235console.log("Rate limited - retry later");236break;237case 500:238case 502:239case 503:240case 504:241console.log("Server error - retry or show maintenance page");242break;243default:244console.log("HTTP error:", error.response.status);245}246} else if (error.request) {247console.log("No response received:", error.message);248} else {249console.log("Request setup error:", error.message);250}251} else {252console.log("Unknown error:", error);253}254}255```256257### Error Response Structure258259Structure of error responses when server returns an error.260261```javascript { .api }262interface AxiosResponse<T = any, D = any> {263/** Response data (error details from server) */264data: T;265/** HTTP status code */266status: number;267/** HTTP status message */268statusText: string;269/** Response headers */270headers: RawAxiosResponseHeaders | AxiosResponseHeaders;271/** Request configuration */272config: InternalAxiosRequestConfig<D>;273/** Native request object */274request?: any;275}276```277278**Usage Examples:**279280```javascript281try {282await axios.post("/api/users", userData);283} catch (error) {284if (axios.isAxiosError(error) && error.response) {285// Server responded with error status286const { status, data, headers } = error.response;287288console.log("Status:", status);289console.log("Error data:", data);290291// Handle API error responses292if (data.errors) {293// Validation errors294data.errors.forEach(err => {295console.log(`${err.field}: ${err.message}`);296});297} else if (data.message) {298// Simple error message299console.log("Error:", data.message);300}301302// Check error-specific headers303const retryAfter = headers["retry-after"];304if (status === 429 && retryAfter) {305console.log(`Rate limited. Retry after ${retryAfter} seconds`);306}307}308}309```310311### Global Error Handling Patterns312313Common patterns for handling errors application-wide.314315**Usage Examples:**316317```javascript318// Global error interceptor319axios.interceptors.response.use(320(response) => response,321(error) => {322if (axios.isAxiosError(error)) {323// Log all axios errors324console.error("Axios Error:", {325url: error.config?.url,326method: error.config?.method,327status: error.response?.status,328message: error.message,329data: error.response?.data330});331332// Handle specific error cases333if (error.response?.status === 401) {334// Redirect to login335localStorage.removeItem("authToken");336window.location.href = "/login";337return Promise.reject(error);338}339340if (error.response?.status >= 500) {341// Show generic server error message342showNotification("Server error occurred. Please try again later.", "error");343}344}345346return Promise.reject(error);347}348);349350// Error boundary for React applications351class ErrorBoundary extends React.Component {352constructor(props) {353super(props);354this.state = { hasError: false, error: null };355}356357static getDerivedStateFromError(error) {358return { hasError: true, error };359}360361componentDidCatch(error, errorInfo) {362if (axios.isAxiosError(error)) {363// Send axios errors to monitoring service364sendToMonitoring({365type: "axios_error",366url: error.config?.url,367status: error.response?.status,368message: error.message,369stack: error.stack370});371}372}373374render() {375if (this.state.hasError) {376return <ErrorFallback error={this.state.error} />;377}378379return this.props.children;380}381}382383// Retry with exponential backoff384async function retryRequest(requestFn, maxRetries = 3) {385for (let attempt = 1; attempt <= maxRetries; attempt++) {386try {387return await requestFn();388} catch (error) {389if (axios.isAxiosError(error)) {390const shouldRetry = error.response?.status >= 500 ||391error.code === "ECONNABORTED" ||392error.code === "ERR_NETWORK";393394if (shouldRetry && attempt < maxRetries) {395const delay = Math.pow(2, attempt) * 1000; // Exponential backoff396console.log(`Request failed, retrying in ${delay}ms (attempt ${attempt}/${maxRetries})`);397await new Promise(resolve => setTimeout(resolve, delay));398continue;399}400}401402throw error; // Re-throw if not retryable or max retries reached403}404}405}406407// Usage408try {409const response = await retryRequest(() =>410axios.get("https://unreliable-api.example.com/data")411);412console.log(response.data);413} catch (error) {414console.log("Request failed after retries:", error.message);415}416```417418### Custom Error Classes419420Extend AxiosError for application-specific error handling.421422**Usage Examples:**423424```javascript425// Custom error for API validation errors426class ValidationError extends axios.AxiosError {427constructor(errors, config, request, response) {428super("Validation failed", "VALIDATION_ERROR", config, request, response);429this.name = "ValidationError";430this.validationErrors = errors;431}432433getFieldErrors() {434return this.validationErrors || [];435}436}437438// Custom error for business logic errors439class BusinessLogicError extends axios.AxiosError {440constructor(businessCode, message, config, request, response) {441super(message, "BUSINESS_ERROR", config, request, response);442this.name = "BusinessLogicError";443this.businessCode = businessCode;444}445}446447// Error factory448function createAppError(axiosError) {449if (axiosError.response?.status === 422) {450return new ValidationError(451axiosError.response.data.errors,452axiosError.config,453axiosError.request,454axiosError.response455);456}457458if (axiosError.response?.data?.businessCode) {459return new BusinessLogicError(460axiosError.response.data.businessCode,461axiosError.response.data.message,462axiosError.config,463axiosError.request,464axiosError.response465);466}467468return axiosError; // Return original error469}470471// Usage in interceptor472axios.interceptors.response.use(473(response) => response,474(error) => {475if (axios.isAxiosError(error)) {476throw createAppError(error);477}478throw error;479}480);481```