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 }); }); });
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With