首页 > 解决方案 > 处理 axios 错误和响应 (vue) 仅适用于一个错误。如何通知多个错误?

问题描述

我有一个与 API 通信(使用 axios 请求)并返回错误的 Vue 应用程序。如果我只收到一个错误,它就可以正常工作,例如当响应如下时:{"error":"passwords.token"}

当我收到这样的累积错误时:

{"message":"The given data was invalid.",
 "errors":{
   "password":["The password confirmation does not match."]}
}

这是我的 Vue 组件和方法 resetPassword() 的代码

methods: {
        resetPassword () {
            this.$vs.loading()

            const payload = {
                userDetails: {
                    email: this.email,
                    password: this.password,
                    password_confirmation: this.password_confirmation,
                    token: this.token
                }
            }

            this.$store.dispatch('auth/resetPassword', payload)
                .then((response) => {
                    this.$vs.loading.close()
                    this.$vs.notify({
                        time: 10000,
                        title: 'Authentication Success',
                        text: response.message.data.message,
                        iconPack: 'feather',
                        icon: 'icon-success-circle',
                        color: 'success'
                    })
                })
                .catch(error => {
                    this.$vs.loading.close()
                    this.$vs.notify({
                        time: 6000,
                        title: 'Authentication Error',
                        text: error.message,
                        iconPack: 'feather',
                        icon: 'icon-alert-circle',
                        color: 'danger'
                    })
                })
        },
    },

标签: javascripterror-handlingprototyperesponse

解决方案


不要有不同的键,因为一次会是一个错误,而其他时候会是两个或三个。例如不要这样做:
1 错误:{错误:“错误消息”}
2 错误:{错误:{“错误_1”:“错误消息 1”} }
如您所见,这非常复杂。只需在其中放一个 syndax,然后即使它一两个左右也可以跟随它。例如你可以让它像

errors: [
   {type: "wrong_user_name_or_password", message: "Wrong user name or password"}
]

然后您可以美化您的通知功能以循环所有错误并显示它们,例如


无法登录。原因:

  • 错误消息

  • 推荐阅读