Axios crashes the Node.js process when the request fails

By

Handle Axios request failures in Node.js with try/catch or a promise rejection handler, and inspect response, request, and setup errors separately.

~~~

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

axios({
  method: 'post',
  url: 'https://...',
  data: JSON.stringify({
		...
  })
})

Axios rejects the promise when the request fails. If nothing handles that rejection, Node.js reports an unhandled rejection and the process may exit.

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

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)
  } else if (error.request) {
    console.error('No response received')
  } else {
    console.error('Could not create the request', error.message)
  }
}

You can also attach .catch() directly to the promise. 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. Do not silently swallow the error.

Tagged: Node.js ยท All topics
~~~

Related posts about node: