首页 > 解决方案 > catch and handle connection refused error using Axios

问题描述

I use Axios for my VueJs app and have a Express REST Api. When my VueJs app is not able to call the backend (connection refused / the node server is not running)

How can I catch this error? I tried to log the error using an interceptor

  instance.interceptors.response.use(res => res, (err) => {
    console.log({ err });

    if (err.response.status === 401) {
      // unauthorized
    }

    return err;
  });

but when logging the err I only get

Error: Network Error

with response: undefined

Should I sign out the user because there is nothing he can do then or should I just show an error alert and let him stay?

标签: javascriptvue.jsaxios

解决方案


axios.interceptors.response.use(
function ( response ) {
    // response data
    return response;
},
function ( error ) {
    let text = '';
    if ( error.response.data ) {
        text = 'error: ' +error.response.data.error.code + ' || ' + error.response.data.error.message;
    } else if (error.message) {
        // network down
        text = error.message + ' || Server is Down ?';
    } else {
        // http status code and data
        text = error.response.status + ' || ' + error.response.data;
    }
    console.log('axios error message: ',text)

     if ( isNetworkError( error ) ) return alert( 'check your connection' );
    throw error;
    // return Promise.reject( error.message );
});    function isNetworkError ( err ) {
return !!err.isAxiosError && !err.response;}

i noticed if server is down or unreachable (like 404) error.response not exist but error.message. i'm checking error.response for (401 etc.) than error.message for (404 or ERR_CONNECTION_REFUSED ) error...


推荐阅读