【发布时间】:2020-07-29 08:01:28
【问题描述】:
我刚刚实现了我的第一个后端文件,我在其中获取了一些用户数据、消息等。 现在,如果没有可用的网络,我想包括错误处理。
我不知道我是否做得对,但这是我目前的做法:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
在我的主视图的 mounted() 函数中,我从上面的后端文件中获取数据:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
我尝试在控制台中检查它是否正常工作,但我得到的只是以下内容:
在 catch 块中我检查
- 响应错误:如 4xx/5xx
- 请求错误:如果我的网络没有及时响应
- 和任何其他错误
这是检查网络是否可用的正确方法吗?还是用户检查错误时会降低用户体验?
我的后端文件包含更多方法。我是否必须为每个方法编写此类请求?
【问题讨论】: