JR Galia
JR Galia

Reputation: 17269

Error Handling ExpressJS and MongoDB

What is the suggested way of error handling in ExpressJS and Mongoose.

app.get('/', function(req, res) {
    Subjects.find({}, function(err, subjects) {
        if (err) {
            return res.json(err);
        }

        res.render('list', {subjects: subjects});
    });
});

I just returned the error in json. Any suggestions? Thanks

Upvotes: 1

Views: 328

Answers (1)

Alex
Alex

Reputation: 38499

It depends on what that error is, but I would usually redirect via res.redirect to an 'Error' url, with details of the error.

You could test for the details of the error, and re-run a query (dependent on what the error is of course) but usually if the callback is throwing an error, it's terminal, so log it, redirect, and inform the user in a nice way.

(Or of course, return JSON and handle your response client side, with no redirect)

EDIT

As per comment from Paul -
I didn't mean to return the exact details to the user about the error.
Simply "Database error" or something like that would be more appropriate, depending on what the error was.

Upvotes: 3

Related Questions