I am using node-mongodb-native driver. I tried
collection.findOne({email: 'a@mail.com'}, function(err, result) {
if (!result) throw new Error('Record not found!');
});
But the error is caught by mongodb driver and the express server is terminated.
What’s the correct way for this case?
=== Edit===
I have the code below in app.js
app.configure('development', function() {
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
Related code in node_modules/mongodb/lib/mongodb/connection/server.js
connectionPool.on("message", function(message) {
try {
......
} catch (err) {
// Throw error in next tick
process.nextTick(function() {
throw err; // <-- here throws an uncaught error
})
}
});
The correct use is not to throw an error, but to pass it to
nextfunction. First you define the error handler:(What’s this talk about
errorbeing depracated? I don’t know anything about that. But even if then you can just useuse. The mechanism is still the same.).Now in your route you pass the error to the handler like this:
Make sure that no other code (related to the response) is fired after
next(myerr);(that’s why I usedreturnthere).Side note: Errors thrown in asynchronous operations are not handled well by Express (well, actually they somewhat are, but that’s not what you need). This may crash your app. The only way to capture them is by using
but this is a global exception handler, i.e. you cannot use it to send the response to the user.