Axios crashes the Node.js process when the request fails

By

Published · Updated

Tagged: Node.js

Why a failed Axios request crashes Node.js, and how to fix it: catch the rejection, read error.response and error.code, set a timeout, and avoid leaking tokens in logs.

I had some code using axios to make a network request:

axios.post('https://example.com/api', {
  name: 'Flavio'
})

When the request failed, the whole Node.js process crashed.

Axios rejects the promise when the request fails. If nothing handles that rejection, Node.js treats it as an uncaught exception, prints the error and exits with code 1. Any timer, server or other work in the process stops with it.

What the crash looks like

With Node.js 22 and Axios 1.21, a request that gets a 404 prints something like this:

node:internal/process/promises:394
    triggerUncaughtException(err, true /* fromPromise */);
    ^

AxiosError: Request failed with status code 404
    at settle (.../node_modules/axios/lib/core/settle.js:19:12)
    ...
  isAxiosError: true,
  code: 'ERR_BAD_REQUEST',
  config: { ... },
  ...
}

After the stack trace, Node dumps the whole error object, including config with every request header. If you send an Authorization header, the token ends up in your logs. More on that below.

What makes Axios reject

Axios rejects the promise in all these cases:

The first one surprises people coming from fetch(), which resolves on a 404 or 500 and only rejects on network errors.

Catch the error with try/catch

With async/await, wrap the request in try/catch:

import axios from 'axios'

try {
  const response = await axios.post('https://example.com/api', {
    name: 'Flavio'
  })

  console.log(response.data)
} catch (error) {
  if (error.response) {
    console.error('Server responded with', error.response.status)
    console.error(error.response.data)
  } else if (error.request) {
    console.error('No response received', error.code)
  } else {
    console.error('Could not create the request', error.message)
  }
}

Check error.response first. When the server answers with a 404, error.request is set too, so if you test error.request first you’ll treat a 404 as “no response”.

You can also attach .catch() to the promise:

axios
  .get('https://example.com/api')
  .then((response) => console.log(response.data))
  .catch((error) => console.error(error.message))

The important part is that the code making the request decides how to handle failure: retry it, return an error response, log it, or let a higher-level handler deal with it. Don’t silently swallow the error.

Forgetting await breaks the try/catch

This is an easy way to still get the crash with a try/catch in place:

async function save() {
  try {
    axios.post('https://example.com/api', { name: 'Flavio' }) // no await!
  } catch (error) {
    console.log('caught') // never runs
  }
}

Without await, the try block finishes right away, before the request fails. The rejection happens later, nobody handles it, and the process exits. Add await (or return the promise to a caller that awaits it).

The same thing happens inside forEach() with an async callback, because forEach() doesn’t wait for promises. Use for...of with await, or Promise.all() with map().

Tell errors apart with error.code

axios.isAxiosError(error) tells you if the error came from Axios, and error.code tells you what happened. These are the codes I got from Axios 1.21 in Node.js:

What happenederror.codeerror.response
Server answered 404ERR_BAD_REQUESTset, status 404
Server answered 500ERR_BAD_RESPONSEset, status 500
Nothing listening on the portECONNREFUSEDundefined
Timeout exceededECONNABORTEDundefined
Malformed URL like https:example.comERR_INVALID_URLundefined

error.status is a shortcut for the response status code, and it’s undefined when there was no response.

For timeouts you get ECONNABORTED by default. Pass transitional: { clarifyTimeoutError: true } in the config if you want ETIMEDOUT instead, which is easier to tell apart from an aborted request.

Don’t throw on some status codes

If a 404 is a normal answer for you (for example “user not found”), use validateStatus to tell Axios which statuses should resolve:

const response = await axios.get('https://example.com/api/users/42', {
  validateStatus: (status) => status < 500
})

if (response.status === 404) {
  console.log('No such user')
}

Now a 404 resolves normally with response.status set to 404, and only 5xx responses and network errors reject.

Set a timeout

The default timeout is 0, which means no timeout. If a server accepts the connection and never answers, your await waits forever. Set one:

const response = await axios.get('https://example.com/api', {
  timeout: 5000 // milliseconds
})

Or set it once for every request with axios.create({ timeout: 5000 }).

Don’t log the whole error object

console.error(error) prints error.config, which includes the request headers. I tested it: with an Authorization: Bearer ... header, the token was right there in the output.

Log the parts you need instead:

console.error(error.message, error.code, error.response?.status)

If you want to log error.toJSON(), pass a redact array in the request config, and Axios masks those config keys in the JSON:

axios.get('https://example.com/api', {
  headers: { Authorization: `Bearer ${token}` },
  redact: ['authorization']
})

A safety net for rejections you missed

You can register a handler for any rejection that nobody caught:

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection:', reason?.message)
})

With this handler, the process no longer exits on an unhandled rejection. That’s handy to log what happened, but it doesn’t replace handling errors where the request is made, because the code that started the request never learns that it failed. See error handling in Node.js for more on exceptions and rejections.

Want me to talk about your product? You can sponsor this site.

Related posts about node: