Reputation: 47
I try to connect to api using axios, in catch state I try to re-throw the error I got from fetching and I want to let my catch from surrounding trycatch to return custom message from that re-thrown error
and here are my console logs
Password is not valid
C:\backend\aplication\Controller\userController.js:20
throw Error(error.response.data.error.toString());
^
Error: Password is not valid
at C:\backend\aplication\Controller\userController.js:20:19
at processTicksAndRejections (node:internal/process/task_queues:96:5)
there "Password is not valid" is the custom error message I was talking about, so I want it to be re-thrown and catched in my trycatch
and that's my code
const Login = async (req, res) => {
const {email, password} = req.body;
try {
axios.post("http://localhost:5000/api/name/user/login", {
email: email,
password: "passwordsarewqewqd"
}).then((response) => {
console.log(response.data);
}, (error) => {
//here I log my custom message and I want to throw it to trycatch to respond correctly
console.log(error.response.data.error.toString());
throw Error(error.response.data.error.toString());
});
} catch (error) {
console.log(error);
res.status(400).json({error: error.message});
}
}
btw, why the code snippet sometimes is in color but sometimes is not?
Upvotes: 1
Views: 207
Reputation: 47
While I was writing this post I realized that I can just pass the error using:
res.status(400).json({
error: error.response.data.error
});
Like so:
const Login = async (req, res) => {
const {email, password} = req.body;
try {
axios.post("http://localhost:5000/api/name/user/login", {
email: email,
password: "passwordsarewqewqd"
}).then((response) => {
console.log(response.data);
}, (error) => {
// here I log my custom message and I want to throw it to trycatch to respond correctly
res.status(400).json({ error: error.response.data.error.toString() });
});
} catch (error) {
console.log(error);
res.status(400).json({error: error.message});
}
}
Upvotes: 1
Reputation: 1
Promises need to be await
ed in try-catch blocks. When awaiting a promise, if it rejects, the error will be thrown. If it is not awaited, the error will returned as a rejected promise.
Inside of the .then
handler, throwing an error is treated like rejecting the promise (source: MDN).
It just so happens that, in this code, there is a .then
which does throw
an error and the promise is not awaited. Therefore, the error that was thrown inside the handler will be turned into a rejected promise (based on how .then
works, source: MDN). Since that rejected promise is not awaited, it will never be treated like a thrown error, and the try-catch block will not know about it.
Recommendation
Avoid mixing try-catch blocks with .then
handlers. Either go for try-catch with async
/await
or only use promises with .then
(and potentially .catch
).
Upvotes: 0