【问题标题】:Handling errors if no network is available如果没有可用的网络,则处理错误
【发布时间】: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
  • 请求错误:如果我的网络没有及时响应
  • 和任何其他错误

这是检查网络是否可用的正确方法吗?还是用户检查错误时会降低用户体验?

我的后端文件包含更多方法。我是否必须为每个方法编写此类请求?

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    在您的后端文件中,我认为您不会对是否有网络连接做出反应。

    仅供参考:这不是后端,而是与后端进行通信 - 后端是您与之通信的代码部分,例如Laravel 代码,一个 API,...

    尝试在 catch 部分的开头添加以下内容:

     if (!error.response) {
        //network error
        console.log('No network connection');
     } else if (error.response) {
       //the rest of your code
                
    

    这应该会在您的控制台中打印出 No network connection。 运行您的应用程序,关闭互联网连接并检查控制台。

    此类代码应始终位于您的后端部分。

    【讨论】:

    • 我去查一下
    【解决方案2】:

    我的回答可能与您的问题不同。 当我使用 Angular 创建 .net 核心 API 时,我使用了三件事来检查是否有网络?

    1. 订阅windows的离线/在线事件
    2. 创建从布局组件到 API 服务器的 signalR 集线器
    3. API 请求失败(这意味着很多事件,但如果 1. 或 2. 案例为真,我知道是什么原因 3. 案例

    【讨论】:

    • 我使用了 windows 的离线/在线事件来改变一个安卓应用的 UI。很好的收获。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2014-10-02
    • 2012-05-16
    • 2013-05-11
    相关资源
    最近更新 更多