【问题标题】:Axios in Nuxt.js is not catch error properlyNuxt.js 中的 Axios 未正确捕获错误
【发布时间】:2023-04-07 22:05:01
【问题描述】:

如上所述,我在 Nuxt.js 上的 Axios 无法正确捕获错误

我需要知道错误,所以我可以提示让用户知道他们的输入不正确,但它只是 console.log 错误代码状态而不是来自我的 API 的消息

这是我的代码

await axios
  .post(
    "API LINK",
    {
      email: user.email,
      password: "123456",
      name: user.name,
      dob: user.dob ?? null,
      gender: user.gender ?? null,
      profileImage: imageUrl ?? user.profileImage,
      userType: user.userType
    }
  )
  .then(res => {
    console.log("success");
    console.log(res);
  })
  .catch(err => {
    console.log('fail');
    console.log(err)
  })

这是 chrome 控制台上的日志

error
add.vue?104b:181 Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:61)

但我对 console.log(err) 的期望是

(This is response from postman)
{
    "message": "Error creating new user.",
    "error": {
        "code": "auth/invalid-password",
        "message": "The password must be a string with at least 6 characters."
    }
}

我不知道发生了什么。

【问题讨论】:

    标签: axios nuxt.js


    【解决方案1】:

    试试这个

     console.log(err.response)
    

    为了使代码更简洁,您可以解构参数:

      .catch(({ response }) => {
        console.log('fail');
        console.log(response)
      })
    

    如果您想使用其他属性名称而不是 response,您可以这样做:

      .catch(({ response: err }) => {
        console.log('fail');
        console.log(err)
      })
    

    问题是当console.log尝试输出错误时,打印的是字符串表示,而不是对象结构,所以你看不到.response属性。

    您可以在这里阅读https://github.com/axios/axios/issues/960

    【讨论】:

    • 非常感谢,伙计。它现在正在工作。顺便说一句,你能向我解释为什么使用 err.response 而不是 err,因为在这个项目之前我总是只使用 err 并且它工作得很好。
    • @Purinut 问题是当 console.log 尝试输出错误时,打印的是字符串表示,而不是对象结构,所以你看不到 .response 属性。在这里你可以了解github.com/axios/axios/issues/960
    【解决方案2】:

    这是使用 try / catch 结构,这是首选方式

      try {
        await axios.post("API LINK", {
          email: user.email,
          password: "123456",
          name: user.name,
          dob: user.dob ?? null,
          gender: user.gender ?? null,
          profileImage: imageUrl ?? user.profileImage,
          userType: user.userType,
        })
        console.log("success", res)
      } catch ({ response }) {
        console.log("fail", response)
      }
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2021-07-26
      • 2017-12-14
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2021-07-05
      相关资源
      最近更新 更多