HTTP Request Error Handling With Axios Interceptors

May 17, 2019

By default, Axios error messages only include the status code. This is a sensible default, but the default error message is often not helpful.

const app = express();
app.get('*', (req, res) => {
  res.status(404).json({ message: `Could not find page ${req.url}` });
const server = await app.listen(3000);

const err = await axios.get('http://localhost:3000/test').
  catch(err => err);
// "Request failed with status code 404"

Thankfully, Axios makes it easy to transform errors so the error message makes sense for your application. Axios interceptors allow you to transform all errors coming out of Axios.

// Create an Axios instance to 
const client = axios.create();
// Interceptors take 2 parameters:
// Axios calls the first function if the request succeeds
// Axios calls the second function if the request fails
  res => res,
  err => {
    throw new Error(;
const err = await client.get('http://localhost:3000/test').
  catch(err => err);
// "Could not find page /test"

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials