Error Handling in Axios using `catch()`

Jun 10, 2020

Axios requests are promises, which means they have a then() function for promise chaining, and a catch() function for handling errors. Below is how you can catch() an error in Axios.

const err = await axios.get('https://httpbin.org/status/404').
  catch(err => err);

err instanceof Error; // true
err.message; // 'Request failed with status code 404'

Axios' catch() behaves exactly the same as the promise catch() function. So you can use promise chaining, and add a catch() at the end to handle any errors that occur in the promise chain.

const err = await axios.get('https://httpbin.org/status/200').
  // Will throw a TypeError because the property doesn't exist.
  then(res => res.doesNotExist.throwAnError).
  catch(err => err);

err instanceof TypeError; // true

You can also use catch() to transform the error, just make sure you rethrow the error afterwards.

let error;
try {
  await axios.get('https://httpbin.org/status/404').catch(err => {
    if (err.response.status === 404) {
      throw new Error(`${err.config.url} not found`);
    }
    throw err;
  });
} catch (err) {
  error = err;
}

error.message; // "https://httpbin.org/status/404 not found"

You can also make Axios transform errors automatically using interceptors.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!
×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!