'How can I show the error from NestJS to my front-end component?
I have a NestJS application which is working properly. I am making a request and throwing a BadRequestException if something fails:
// my-service.ts
try {
return await signUp(...);
} catch (err) {
throw new BadRequestException({
description: err.message,
});
// have also tried...
throw new BadRequestException(err.message);
}
In the network tab, I can see I'm getting a good error:
{"description":"An account with the given email already exists."}
I am using VueJS for my front-end, and while I am getting a 400 error back, I'm only able to return a generic error message.
Here is what my request looks like:
// 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);
}
How can I return the error I am seeing in NestJS, all the way back to Vue so I can render it to the screen?
Solution 1:[1]
Here on this documentation you can se how to do error handling on axios:
https://axios-http.com/docs/handling_errors
So probably you can do something like this to access the message from 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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DSabalsa |
