javascript - 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...
推荐阅读
- intellij-idea - 没有行号的 Flutter IntelliJ 错误
- angular - 错误:PERMISSION_DENIED - Angular 7 和 Firebase
- php - 如何修复左右侧边栏并保持中心主要内容可向上滚动?
- python - 熊猫多索引数据框条件列连接
- javascript - 仅通过更改文本来进行 HTML 和 JavaScript 导航
- performance - 查找具有至少一个具有特定属性的子节点的有效方法
- python - 将字典列表转换为更适合下拉列表的格式
- javascript - JQuery on keydown 事件聚焦到一个按钮似乎自动按下按钮?
- css - IE11 中的问题(使用 flexbox),不会停留在下方,而是覆盖第一行
- python - python tkinter for循环使用并且图像未加载