Reputation: 126
how can I catch an error in NodeJS or create own error code and send it to the frontend to inform the user? In the following code I am looking into the database result if there were any data deleted and try to send an error code. How can I send the error code to my react frontend? Maybe using response.json("Not deleted any user"). Tried it already out. How can I prevent my server from crashing? If the sql is not correcting because there was no id send to delete it is crashing. Thanks for the answers for this two cases.
db.getConnection((err, connection) => {
if (err) throw err;
connection.query(
"DELETE FROM users where users_id = ?",
[2],
(err, rows) => {
connection.release();
if (rows.affectedRows == 0) {
throw err;
}
if (err) throw err;
if (!err) {
res.redirect("/");
} else {
console.log(err);
}
console.log("Daten gelöscht", rows.affectedRows);
}
);
});
Upvotes: 0
Views: 691
Reputation: 365
You should use a try, catch block. If you want to throw a custom exception, you can do something like
throw new NotFoundException("Record with the given id Not Found...!!!"):
I use it in nestjs I am not fully sure that this will work for you but you can try :)
Upvotes: 1