Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  162] [ 6]  / answers: 1 / hits: 70400  / 9 Years ago, thu, february 11, 2016, 12:00:00

I am using Sequelize ORM in Node/Express.



I have two tables, User and Item. Item has a foreign key linked to UserId.



When I try to create an Item with a UserId that is invalid (not present in Users table) a SequelizeForeignKeyConstraintError is thrown and leads to crashing of the application due to unhandled.



The problem I have is this:



Where do I handle the error?



Here is my code.



.post(function(req,res){
models.Item.create({
title : req.body.title,
UserId : req.body.UserId
}).then(function(item){
res.json({
Message : Created item.,
Item : item
});
});
});

More From » express

 Answers
25

If you want to handle the specific error, attach a .catch handler



models.Item.create({
title : req.body.title,
UserId : req.body.UserId
}).then(function(item){
res.json({
Message : Created item.,
Item : item
});
}).catch(function (err) {
// handle error;
});


If you want to handle errors more generally (i.e. show a nice error message, instead of killing your server, you might want to have a look at unhandledexception



https://nodejs.org/api/process.html#process_event_uncaughtexception



If you are using express, it also contains some error handling facilities http://expressjs.com/en/guide/error-handling.html


[#63354] Tuesday, February 9, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annie

Total Points: 483
Total Questions: 97
Total Answers: 107

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
;