node.js - 使用 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;
}
解决方案
返回的正文不会直接出现在捕获的错误消息中,即它可能是一个传统的错误,它可以是对象、字符串或异常。
您将需要使用响应的主体(状态代码为 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 中使用它,因为它可以防止单个意外的空值破坏整个视图模型。
推荐阅读
- c# - 如何在 ASP.NET 控制器方法中显式
- jquery - 使用 rgb 在鼠标移动时更改颜色以获取色谱
- c# - 如何扩展服务层方法
- python - 将带有零星日期的年均值输入到有组织的日期时间数据框中
- python - Python Webscraping:为什么我无法使用 Selenium 和 ChromeDriver 与 Linkedin 上的搜索栏交互?
- json - 使用 UrlFetchApp.fetch() 的请求如何计入 AlphaVantage API 的速率限制?
- javascript - 制作带有回调的 JavaScript 函数
- c++ - 是否适合为每个“类型”创建一个带有构造函数重载的模板类
- reactjs - 使用 toHaveBeenCalledWith 检查 EventTarget
- azure-active-directory - 将 AAD 克隆到另一个启用了 B2C 功能的租户