简体   繁体   中英

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?

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

try this

axios.interceptors.response.use(
  function(response) {
  return response;
 },
 function(err) {
   if (err.response.status === 401) {
     // unauthorized
   }

    return Promise.reject(err);
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM