简体   繁体   中英

Functionall approach to error handling

I found this snippet here: http://www.nodewiz.biz/nodejs-error-handling-pattern/

It supposed to handle errors better than normal way in node.js. But I fail to understand how it works and why it is better than plain if(err) ?


Functional Approach

An example using the Express.js feramework, define a function that returns an error handler:

function error(res,next) {
    return function( err, result ) {
        if( err ) {
            res.writeHead(500); res.end(); console.log(err);
        }
        else {
            next(result)
        }
    }
}

Which allows you to do this;

app.get('/foo', function(req,res) {
    db.query('sql', error(res, function(result) {
        // use result
    }));
});

Covering this method only as an example, do not use this method for production code, unless you actually handle the error properly.

"It supposed to handle errors better than normal way in node.js. But I fail to understand how it works..."

How it works is that it receives the res object and a function (provided by you) that gets invoked if the result was successful.

It then returns a function that is passed to db.query() as the callback. So that callback actually receives the err and result .

If it finds an err , it handles sending the appropriate 500 response for you. If it doesn't find an error, it invokes the function you provided passing it the result . That way you know that if the function you provided runs, it was because there was no error.


"...and why it is better than plain if(err)?"

It isn't better. It's just different. It is nice if the error handling will always be the same in that you can update it in one spot, and any code that uses it will benefit from the update.

However, a simple function abstraction could do the same.

function error(res, err) {
    if( err ) {
        res.writeHead(500); res.end(); console.log(err);
        return true
    }
    return false
}

Which allows you to do this;

app.get('/foo', function(req,res) {
    db.query('sql', function(err, result) {
        if (error(res, err))
            return;

        // use the result
    }));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM