Home > Net >  Changing the default exception message in Axios
Changing the default exception message in Axios

Time:06-07

When hitting an HTTP error, Axios only states the HTTP status code in the thrown exception message. I want the exception message to include the request URL, too.

I tried to implement what I want using the following interceptor:

axios.interceptors.response.use(
    response => response,
    error => {
        throw `HTTP ${error.response.status} by ${error.request.url}`;
    }
);

The error callback doesn't get triggered upon HTTP errors. Any ideas?

CodePudding user response:

Try to use Promise.reject to replace throw. The following code works for me. Tested in Chrome.

    axios.interceptors.response.use(
        function (response) {
          return response;
      }, 
      function (error) {
          return Promise.reject(`HTTP ${error.response.status} by ${error.response.config.url}`);
   });

Also, you can simply catch the exception like -

    let res = await axios.post(...)
                  .catch(error => { 
                       console.log(error.response); 
                       console.log(error.request); 
                   });

You have access to all the error details as in interceptor.

  • Related