Lev Lev - 4 months ago 46
Node.js Question

When to use error middleware function in NODE

Should I use expresses eror handling middleware function for a case of missing fields in a POST request ?

function (req, res, next) {

if (!req.body.mandatoryField){
var err = new Error("missing field);
next(err); // send response from error middleware


Or should I save it for cases that catually throw an error :


In other words, is throwing an error for bad input in a POST request overkill ?

Or should I just respond directly with a 400 status response without throwing and an error.


I wouldn't. I would save Middleware error handling to send errors to a logging service. Typically you intercept a general error and simply log it before moving on. If you do it as a middleware, you will intercept every request, which for most cases will be unnecessary and brittle.

Typically, these sort of validations would happen on the client using jQuery, that way you are saving a trip to the db.

Here is how I use middleware to handle errors:

//uncaught exception in the application/api, etc.   Express will pass the err param.  This doesn;t look for specific errors, it will log any general error it sees.
app.use(function(err, req, res, next) {
    //send to logging service.
//uncaught exception in Node
if (process.env.NODE_ENV === 'production' || appConfig.env === 'production') { // [2]
    process.on('uncaughtException', function(err) {
        console.error(err.stack); // [3]
        //log error, send notification, etc

    }, function(err) {
        if (err) {console.error(err);}
        process.exit(1); // [5]