Reputation: 311
I am creating an application in SailsJS. I am getting errors, like, typeError or 500 errors when some error occurs in DB related queries.I am using MongoDB. Is there any way that I can catch this error in server-side.
Now, these errors are crashing my server. And the server stops. I have to restart the server again.
Please help me in fixing this issue. Thanks in advance.
Upvotes: 1
Views: 2342
Reputation: 1083
If you are using Sails 0.10.x you can pass errors to next handler:
controlleAction:function(req,res, next){
var invalidParams = {};//whatever's causing the error
Model
.create(invalidParams)
.exec(function(err,created){
if(err) return next(err);
return res.json(created);
});
}
And then process errors in "Custom Responses"
Upvotes: 0
Reputation: 101
Please be careful there:
controlleAction:function(req,res){
var invalidParams = {};//whatever's causing the error
Model
.create(invalidParams)
.exec(function(err,created){
// return res.json()
if(err) return res.json(err);
return res.json(created);
});
}
// The difference is in the return
if(err) return res.json(err);
If you have an error, without the return, the server will crash because it would try to send two responses one with the error and another one with the created object.
Upvotes: 1
Reputation: 1711
Most likely waterline is throwing an exception and you're not catching it. Here's some code to fix that:
controlleAction:function(req,res){
var invalidParams = {};//whatever's causing the error
Model
.create(invalidParams)
.exec(function(err,created){
if(err) res.json(err);
res.json(created);
});
}
you could also use the promise syntax
controlleAction:function(req,res){
var invalidParams = {};//whatever's causing the error
Model
.create(invalidParams)
.then(function(created){
res.json(created);
})
.catch(function(err){
res.json(err);
});
}
If you're trying to catch every global error in your entire application, in your app.js, there's a line like this:
// Start server
sails.lift(rc('sails'));
surround that line with a try catch block like so:
try{
// Start server
sails.lift(rc('sails'));
}catch(e){
console.dir(e);
}
Upvotes: 1