首页 > 解决方案 > 使用 vue js 前端从 nodejs 后端 api 捕获错误

问题描述

我正在使用 Vue.js,我需要捕获我的后端 api 的错误。

当我尝试捕获错误消息时,我收到一个错误:

[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'message' of undefined"

我究竟做错了什么?

我有一个nodejs路由器测试:

router.post("/register", async (req, res) => {
  const email = 'teste';
  if (email) {
    //Throw error to test
    return res.status(400).send({
      data: {
        message: "Já existe uma conta com esse email no nosso sistema",
      },
    });
  }
 })

在我的 vuejs 视图中,我有:

 try {
    //AuthenticationService.register is an axios post 
    const response = await AuthenticationService.register({
            nome: this.nome,
            email: this.email,
            password: this.password,
    });
 } catch (err) {
          console.log("erro", err);
          this.error = err.data.message;
 }

标签: node.jsvue.js

解决方案


返回的正文不会直接出现在捕获的错误消息中,即它可能是一个传统的错误,它可以是对象、字符串或异常。

您将需要使用响应的主体(状态代码为 400 将引发错误,但仍需要使用响应的主体并将其解析为 JSON)。

特别是在 axios 中,此响应作为属性包含在错误中,即err.response. 假设您没有修改现有的 axios 行为,它还会自动为您解析 JSON,因此您可以简单地这样做:

try {
   //AuthenticationService.register is an axios post 
   const response = await AuthenticationService.register({
           nome: this.nome,
           email: this.email,
           password: this.password,
   });
} catch (err) {
         console.log("erro", err);
         this.error = err.response.data.message;
}

如果您使用的是最新版本的 Node,您可以使用新的 null 传播运算符来提高 Vue 中的安全性:

try {
   //AuthenticationService.register is an axios post 
   const response = await AuthenticationService.register({
           nome: this.nome,
           email: this.email,
           password: this.password,
   });
} catch (err) {
         console.log("erro", err);
         this.error = err?.response?.data?.message;
}

这意味着如果任何属性为 null,它将传播 null 而不是引发错误并可能停止您的程序流。这通常也称为可选链接,我强烈推荐在 Vue 中使用它,因为它可以防止单个意外的空值破坏整个视图模型。


推荐阅读