Error handling principles for Node.js + Express.js applications?

前端 未结 3 1313
有刺的猬
有刺的猬 2020-12-04 04:12

It seems like error reporting/handling is done differently in Node.js+Express.js applications compared to other frameworks. Am I correct in understanding that it works as fo

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 05:03

    Error handling in Node.js is generally of the format A). Most callbacks return an error object as the first argument or null.

    Express.js uses middleware and the middleware syntax uses B) and E) (mentioned below).

    C) is bad practice if you ask me.

    app.get('/home', function(req, res) {
        // An error occurs
        throw err;
    });
    

    You can easily rewrite the above as

    app.get('/home', function(req, res, next) {
        // An error occurs
        next(err);
    });
    

    Middleware syntax is valid in a get request.

    As for D)

    (07:26:37 PM) tjholowaychuk: app.error is removed in 3.x

    TJ just confirmed that app.error is deprecated in favor of E

    E)

    app.use(function(err, req, res, next) {
      // Only handle `next(err)` calls
    });
    

    Any middleware that has a length of 4 (4 arguments) is considered error middleware. When one calls next(err) connect goes and calls error-based middleware.

提交回复
热议问题