我有一个工作正常的NestJS应用程序。如果有什么失败,我将发出请求并抛出一个BadRequestException
:
// my-service.ts
try {
return await signUp(...);
} catch (err) {
throw new BadRequestException({
description: err.message,
});
// have also tried...
throw new BadRequestException(err.message);
}
在“网络”选项卡中,我可以看到我得到了一个很好的错误:
{“description”:“具有给定电子邮件的帐户已经存在”}
我在前端使用VueJS,当我得到一个400个错误时,我只能返回一个通用错误消息。
以下是我的请求:
// my-service.js
const client = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Cache-Control': null,
'X-Requested-With': null,
},
});
...
try {
const response = await client.post(`/v1/auth/signup`, user, {
headers: { Authorization: `Bearer ${token}` },
});
console.log('resp: ', response);
} catch (err) {
console.log('err: ', err); // Request failed with status code 400
return Promise.reject(err);
}
我如何返回在NestJS中看到的错误,一直返回到Vue,以便将其呈现到屏幕上?
发布于 2022-04-25 00:54:57
在本文档中,您可以了解如何对axios进行错误处理:
https://axios-http.com/docs/handling_errors
因此,您可能可以这样做来访问来自NestJS的消息:
try {
const response = await client.post(`/v1/auth/signup`, user, {
headers: { Authorization: `Bearer ${token}` },
});
console.log('resp: ', response);
} catch (err) {
if (err.response) {
console.log(err.response.data);
} else {
console.log(err);
}
}
https://stackoverflow.com/questions/71991973
复制相似问题