Skip to content

Error handling ​

axios may throw many different types of errors. Some of these errors are caused by axios itself, while others are caused by the server or the client. The following table lists the general structure of the thrown error:

PropertyDefinition
messageA quick summary of the error message and the status it failed with.
nameThe error name: usually AxiosError, CanceledError for cancellations, or the original name of a wrapped error. Use axios.isAxiosError(error) to identify Axios errors and axios.isCancel(error) to detect cancellations.
stackProvides the stack trace of the error.
configAn axios config object with specific instance configurations defined by the user from when the request was made.
codeRepresents an axios identified error. The table below lists out specific definitions for internal axios error.
statusHTTP response status code. See here for common HTTP response status code meanings.

Below is a list of potential axios identified error

CodeDefinition
ERR_BAD_OPTION_VALUEInvalid or unsupported value provided in axios configuration.
ERR_BAD_OPTIONInvalid option provided in axios configuration.
ECONNABORTEDTypically indicates that the request has been timed out (unless transitional.clarifyTimeoutError is set) or aborted by the browser or its plugin.
ETIMEDOUTRequest timed out due to exceeding the default axios timelimit. transitional.clarifyTimeoutError must be set to true, otherwise a generic ECONNABORTED error will be thrown instead
ECONNREFUSEDThe server refused the connection. Set by the Node.js http adapter, with the original system error on error.cause; the xhr and fetch adapters report ERR_NETWORK instead.
ERR_NETWORKNetwork-related issue. In the browser, this error can also be caused by a CORS or Mixed Content policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console.
ERR_FR_TOO_MANY_REDIRECTSRequest is redirected too many times; exceeds max redirects specified in axios configuration.
ERR_DEPRECATEDDeprecated feature or method used in axios.
ERR_BAD_RESPONSEResponse cannot be parsed properly or is in an unexpected format. Usually related to a response with 5xx status code.
ERR_BAD_REQUESTThe request has an unexpected format or is missing required parameters. Usually related to a response with 4xx status code.
ERR_CANCELEDFeature or method is canceled explicitly by the user using an AbortSignal (or a CancelToken).
ERR_NOT_SUPPORTFeature or method not supported in the current axios environment.
ERR_INVALID_URLInvalid URL provided for axios request.
ERR_FORM_DATA_DEPTH_EXCEEDEDAn object exceeds the configured maxDepth while serializing params or form data. Default limit is 100 levels. Parsing FormData into JSON, by axios.formToJSON() or when a spec-compliant FormData (one with an entries() method) or HTML form is sent with Content-Type: application/json, has a fixed limit of 100 levels that maxDepth does not change. See paramsSerializer and formSerializer.

Handling errors ​

The default behaviour of axios is to reject the promise if the request fails. However, you can also catch the error and handle it as you see fit. Below is an example of how to catch an error:

js
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);
});

Malformed HTTP(S) URLs ​

axios rejects an http: or https: request url or baseURL that omits // after the protocol. For example, https:example.com and https:/example.com reject with an AxiosError whose code is ERR_INVALID_URL, instead of being silently normalized by the browser or Node.js URL parser. Use a well-formed URL such as https://example.com.

The message names the offending URL, for example:

text
Invalid URL "https:example.com": missing "//" after protocol

This behavior prevents malformed URLs from bypassing baseURL or URL allowlists. The reported URL is control-character-normalized and redacts credentials, query parameter values, and fragment contents. It retains the scheme, host, path, and query parameter names so the request remains identifiable. Message-level redaction is unconditional because AxiosError.message is always included by toJSON(); the request config's redact option cannot clean an already-created message.

Using the validateStatus config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.

js
axios.get("/user/12345", {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  },
});

Using the toJSON method, you can get an object with more information about the error.

js
axios.get("/user/12345").catch(function (error) {
  console.log(error.toJSON());
});

To avoid logging secrets from error.config, pass a redact array in the request config. Matching config keys are masked case-insensitively at any depth when AxiosError#toJSON() is called. Objects other than plain objects and AxiosHeaders that have a toJSON() method, such as URL objects, are serialized as-is and not scanned, and credentials inside URL strings are not matched. List the parent key, such as auth or proxy, to mask the whole value.

js
axios.get("/user/12345", {
  headers: { Authorization: "Bearer token" },
  redact: ["authorization"]
}).catch(function (error) {
  console.log(error.toJSON().config.headers.Authorization); // [REDACTED ****]
});

Response duration on errors ​

When an error carries a response, such as a non-2xx status rejected by validateStatus, error.response.duration holds the elapsed adapter time in milliseconds. Not every error has a response: network errors, timeouts, and cancellations have no error.response and therefore no duration. Check for a response before reading it:

js
try {
  await axios.get('/users');
} catch (error) {
  if (axios.isAxiosError(error) && error.response) {
    console.log(error.response.status, error.response.duration);
  }
}

Strict JSON parsing failures keep the duration on the response attached to the error. See Response duration for what the value measures.

Wrapped error stacks ​

When axios wraps a lower-level error, such as a Node.js socket or DNS failure, the original error remains available as error.cause. The wrapper's error.stack also includes the wrapped error's stack after a Caused by: line, so error reporters that read only stack can see the underlying failure. The axios frames and reconstructed caller frames come first, followed by the wrapped stack verbatim:

text
Error: getaddrinfo ENOTFOUND api.example.invalid
    at AxiosError.from (.../axios/lib/core/AxiosError.js)
    ...
    at Axios.request (.../axios/lib/core/Axios.js)
    at async loadUser (/app/users.js:4:5)
Caused by: Error: getaddrinfo ENOTFOUND api.example.invalid
    at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:...)

Use error.cause for programmatic access; it is the same original error object:

js
try {
  await axios.get('https://api.example.invalid/users');
} catch (error) {
  if (axios.isAxiosError(error) && error.cause) {
    console.log(error.cause.code); // e.g. 'ENOTFOUND'
  }
}

Keep the following in mind:

  • The combined string is also returned by error.toJSON().stack. It is verbatim diagnostic output: redact does not sanitize stack strings.
  • Cause-aware tooling that already prints error.cause may show some stack content twice.
  • Only errors wrapped through AxiosError.from() whose cause has a usable stack gain a section. Missing, empty, or unreadable stacks are skipped.
  • Wrapping an already-wrapped error adds another nested section each time, so the string grows with every wrap.
  • A stack passed in the customProps argument of AxiosError.from() still replaces the generated stack.
  • The Caused by: marker is diagnostic text, not a stable format to parse.
  • Wrapping cannot recover details the platform never provided. For example, a browser XHR Network Error generally has no underlying error stack, so hidden CORS, DNS, or TLS causes remain unavailable.

Handling timeouts ​

When a request exceeds its configured timeout, axios rejects with ECONNABORTED by default. Set transitional.clarifyTimeoutError: true to receive ETIMEDOUT instead, which makes timeout errors easier to distinguish from other aborts.

js
async function fetchWithTimeout() {
  try {
    const response = await axios.get("https://example.com/data", {
      timeout: 5000, // 5 seconds
      transitional: {
        // set to true if you prefer ETIMEDOUT over ECONNABORTED
        clarifyTimeoutError: true,
      },
    });

    console.log("Response:", response.data);
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
        console.error("Request timed out. Please try again.");
        return;
      }

      console.error("Axios error:", error.message);
      return;
    }

    console.error("Unexpected error:", error);
  }
}

Always set a timeout in production

Without one, a stalled request can hang indefinitely. See timeout and transitional.clarifyTimeoutError for the matching config options.

axios is provided under MIT license