【问题标题】:Catch error with try catch block and display使用 try catch 块捕获错误并显示
【发布时间】:2021-10-08 08:16:59
【问题描述】:

node js 后端中的错误处理中间件:

app.use((error, req, res, next) => {
  console.log(error);
  const status = error.statusCode || 500;
  const message = error.message;
  const data = error.data;
  res.status(status).json({ message: message, data: data });
});

我的应用中有以下 try catch 块:

    userLogin() {
    //axios vue instance
      this.$http
        .post("/auth/signup", this.formData)
        .then((res) => {
          // res.status == 201 ? (this.formData = {}) : "";
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
          console.log(err.data.data);
          console.log(err.data.msg);
        });
    },

上述catch块的输出如下: [![在此处输入图片说明][2]][2]

当我的 rest api 以以下格式发送消息时(见网络 > 预览)

{
  message: "Validation failed.",
  …
}
data: [{
  location: "body",
  param: "email",
  value: "test@test.com",
  msg: "E-Mail address already exists!"
}]
message: "Validation failed."

我想访问数据数组并打印它的内容。 如何访问data

【问题讨论】:

    标签: javascript node.js vue.js error-handling axios


    【解决方案1】:

    更易读的格式

    async userLogin() {
    
       try {
    
           // Call the server
           const {data} = await this.$http.post("/auth/signup", this.formData);
    
           // If you want message
           let message = data.message;
    
           // If you want the data object, ex data: [{location: "body"....}]
           let dataObject = data.data;
    
       } catch (e) {
    
          // In case of error
          console.log(err.response);
    
       }
    };
    

    【讨论】:

      【解决方案2】:

      我们可以捕获自定义错误消息:

      userLogin() {
        this.$http
          .post("/auth/signup", this.formData)
          .then((res) => {
            // res.status == 201 ? (this.formData = {}) : "";
            console.log(res);
          })
          .catch((err) => {
            console.log(err.response.data.data);
          });
      },

      【讨论】:

        【解决方案3】:

        Axios 存储实际的 response in its data prop(与响应内容中的 API 的 data 属性无关),因此您可以像这样访问您的 data 属性:

        this.$http.post('/auth/signup', this.formData)
          .then((res) => {
            const apiResponse = res.data
            console.log(apiResponse.data) // logs `data` property from API response contents
          })
          .catch((err) => {
             /*...*/
          })
        

        【讨论】:

          猜你喜欢
          • 2014-03-04
          • 1970-01-01
          • 2021-11-05
          • 1970-01-01
          • 2019-02-11
          • 2016-05-29
          • 1970-01-01
          • 2022-12-21
          • 2015-03-31
          相关资源
          最近更新 更多