HTTP Request Error Handling With Axios Interceptors

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); 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.

const client = axios.create(); 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); err.message;

More Axios Tutorials