[英]catch and handle connection refused error using Axios
I use Axios for my VueJs app and have a Express REST Api.我将 Axios 用于我的 VueJs 应用程序,并有一个 Express REST Api。 When my VueJs app is not able to call the backend (connection refused / the node server is not running)
当我的 VueJs 应用程序无法调用后端时(连接被拒绝/节点服务器未运行)
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但是在记录
err
时我只得到
Error: Network Error
错误:网络错误
with response: undefined
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 .我注意到如果服务器关闭或无法访问(如 404) error.response不存在但error.message 。 i'm checking error.response for (401 etc.) than error.message for (404 or ERR_CONNECTION_REFUSED ) error...
我正在检查 error.response(401 等)而不是 error.message(404 或 ERR_CONNECTION_REFUSED)错误...
try this试试这个
axios.interceptors.response.use(
function(response) {
return response;
},
function(err) {
if (err.response.status === 401) {
// unauthorized
}
return Promise.reject(err);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.