Skip to main content
Axios provides a robust error handling system that helps you identify and respond to different types of failures in your HTTP requests.

Basic error handling

Handle errors using try/catch or promise .catch():
try {
  const response = await axios.get('/user/12345');
  console.log(response.data);
} catch (error) {
  console.error('Error:', error.message);
}

Error object structure

When a request fails, Axios provides a detailed error object:
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser
      // and an instance of http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

AxiosError properties

All Axios errors have the following properties:
PropertyTypeDescription
messagestringError message summarizing what went wrong
namestringAlways 'AxiosError' for Axios errors
codestringAxios-specific error code (e.g., 'ERR_NETWORK')
configobjectThe request configuration that was used
requestobjectThe request object (XMLHttpRequest or http.ClientRequest)
responseobjectThe response from the server (if received)
statusnumberHTTP status code (if response was received)
stackstringStack trace of the error

Error types

Axios categorizes errors into three main types:

1. Response errors

The server responded with a status code outside the 2xx range:
try {
  await axios.get('/user/12345');
} catch (error) {
  if (error.response) {
    // Server responded with error status
    console.log('Status:', error.response.status);
    console.log('Data:', error.response.data);
    console.log('Headers:', error.response.headers);
    
    // Handle specific status codes
    if (error.response.status === 404) {
      console.log('User not found');
    } else if (error.response.status === 401) {
      console.log('Unauthorized');
    }
  }
}

2. Request errors

The request was made but no response was received:
try {
  await axios.get('/user/12345');
} catch (error) {
  if (error.request) {
    // Network error, timeout, or no response
    console.log('No response received');
    console.log('Request:', error.request);
  }
}

3. Setup errors

An error occurred while setting up the request:
try {
  await axios.get('/user/12345');
} catch (error) {
  if (!error.response && !error.request) {
    // Error in request configuration
    console.log('Setup error:', error.message);
  }
}

Error codes

Axios provides specific error codes to identify issues:
CodeDescription
ERR_BAD_OPTION_VALUEInvalid value provided in axios configuration
ERR_BAD_OPTIONInvalid option provided in axios configuration
ERR_NOT_SUPPORTFeature or method not supported in the current environment
ERR_DEPRECATEDDeprecated feature or method used
ERR_INVALID_URLInvalid URL provided for request
ECONNABORTEDRequest timed out or aborted by browser
ERR_CANCELEDRequest canceled by user using AbortSignal or CancelToken
ETIMEDOUTRequest timed out (when transitional.clarifyTimeoutError is true)
ERR_NETWORKNetwork-related issue or CORS/Mixed Content policy violation
ERR_FR_TOO_MANY_REDIRECTSToo many redirects
ERR_BAD_RESPONSEResponse cannot be parsed properly (usually 5xx status)
ERR_BAD_REQUESTRequest has unexpected format or missing parameters (usually 4xx status)

Checking error codes

try {
  await axios.get('/user/12345', { timeout: 5000 });
} catch (error) {
  if (error.code === 'ECONNABORTED') {
    console.log('Request timed out');
  } else if (error.code === 'ERR_NETWORK') {
    console.log('Network error');
  } else if (error.code === 'ERR_CANCELED') {
    console.log('Request was canceled');
  }
}

Type checking

isAxiosError

Check if an error is an Axios error:
import axios from 'axios';

try {
  await axios.get('/user/12345');
} catch (error) {
  if (axios.isAxiosError(error)) {
    // TypeScript now knows this is an AxiosError
    console.log('Axios error:', error.response?.status);
  } else {
    // Handle non-Axios errors
    console.log('Unexpected error:', error);
  }
}

TypeScript support

import axios, { AxiosError } from 'axios';

interface ErrorResponse {
  message: string;
  code: string;
}

try {
  const { data } = await axios.get('/user/12345');
} catch (error) {
  if (axios.isAxiosError<ErrorResponse>(error)) {
    // error.response.data is typed as ErrorResponse
    console.log(error.response?.data.message);
    console.log(error.response?.data.code);
  } else {
    console.error('Unexpected error:', error);
  }
}

Handling timeouts

Handle request timeouts specifically:
async function fetchWithTimeout() {
  try {
    const response = await axios.get('https://example.com/data', {
      timeout: 5000 // 5 seconds
    });
    console.log('Response:', response.data);
  } catch (error) {
    if (axios.isAxiosError(error) && error.code === 'ECONNABORTED') {
      console.error('Request timed out!');
    } else {
      console.error('Error:', error.message);
    }
  }
}
For clearer timeout errors, enable clarifyTimeoutError:
const instance = axios.create({
  timeout: 5000,
  transitional: {
    clarifyTimeoutError: true // Use ETIMEDOUT instead of ECONNABORTED
  }
});

try {
  await instance.get('/slow-endpoint');
} catch (error) {
  if (error.code === 'ETIMEDOUT') {
    console.error('Request timed out');
  }
}

Custom status validation

By default, Axios treats status codes outside 2xx as errors. Customize this behavior:
axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if status code is less than 500
  }
})
.then(function (response) {
  if (response.status === 404) {
    console.log('User not found, but not throwing error');
  }
});
axios.get('/endpoint', {
  validateStatus: () => true
})
.then((response) => {
  // Handle any status code here
  if (response.status >= 400) {
    console.log('Error status:', response.status);
  }
});

Error recovery patterns

Retry logic

Automatically retry failed requests:
async function fetchWithRetry(url, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await axios.get(url);
      return response.data;
    } catch (error) {
      const isLastAttempt = i === retries - 1;
      
      if (isLastAttempt || !shouldRetry(error)) {
        throw error;
      }
      
      // Wait before retrying (exponential backoff)
      await new Promise(resolve => 
        setTimeout(resolve, Math.pow(2, i) * 1000)
      );
    }
  }
}

function shouldRetry(error) {
  // Retry on network errors or 5xx status codes
  return !error.response || error.response.status >= 500;
}

Fallback values

Provide fallback data when requests fail:
async function getUserData(userId) {
  try {
    const { data } = await axios.get(`/users/${userId}`);
    return data;
  } catch (error) {
    console.warn('Failed to fetch user, using default:', error.message);
    return {
      id: userId,
      name: 'Guest User',
      email: null
    };
  }
}

Graceful degradation

async function loadDashboard() {
  const [users, posts, analytics] = await Promise.allSettled([
    axios.get('/api/users'),
    axios.get('/api/posts'),
    axios.get('/api/analytics')
  ]);
  
  return {
    users: users.status === 'fulfilled' ? users.value.data : [],
    posts: posts.status === 'fulfilled' ? posts.value.data : [],
    analytics: analytics.status === 'fulfilled' ? analytics.value.data : null
  };
}

Error serialization

Get a detailed error object for logging:
axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

// Output includes:
// {
//   message: 'Request failed with status code 404',
//   name: 'AxiosError',
//   stack: '...',
//   config: { ... },
//   code: 'ERR_BAD_REQUEST',
//   status: 404
// }

Centralized error handling

Use interceptors for application-wide error handling:
axios.interceptors.response.use(
  (response) => response,
  (error) => {
    // Log all errors
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message
    });
    
    // Handle specific errors globally
    if (error.response?.status === 401) {
      // Redirect to login
      window.location.href = '/login';
    } else if (error.response?.status === 403) {
      // Show permission error
      alert('You do not have permission to perform this action');
    }
    
    return Promise.reject(error);
  }
);

Build docs developers (and LLMs) love