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"
err.message;

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
client.interceptors.response.use(
  res => res,
  err => {
    throw new Error(err.response.data.message);
  }
)
const err = await client.get('http://localhost:3000/test').
  catch(err => err);
// "Could not find page /test"
err.message;

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

More Axios Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!