Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to handle the error in a sequelize ORM query statement?

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             });         });     }); 
like image 217
Josh Hale Avatar asked Feb 11 '16 11:02

Josh Hale


People also ask

How do I write a Sequelize query?

As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the sequelize. query method. By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).

What does raw true do in Sequelize?

According to the doc : If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.


1 Answers

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

like image 169
Jan Aagaard Meier Avatar answered Oct 29 '22 14:10

Jan Aagaard Meier