我什么时候应该使用错误处理中间件功能

时间:2016-10-07 13:53:55

标签: node.js express

在示例A中的中间件函数中捕获错误和响应有什么好处。

示例A

tamer@tamer-Inspiron-N5110:/media/tamer/Work/conFusion/test$ protractor protractor.conf.js
[15:23:48] I/direct - Using ChromeDriver directly...
[15:23:48] I/launcher - Running 1 instances of WebDriver
[15:23:48] E/direct - Error code: 135
[15:23:48] E/direct - Error message: Could not find chromedriver at /home/tamer/.npm-global/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22
[15:23:48] E/direct - Error: Could not find chromedriver at /home/tamer/.npm-global/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22
    at Direct.getNewDriver (/home/tamer/.npm-global/lib/node_modules/protractor/built/driverProviders/direct.js:65:27)
    at Runner.createBrowser (/home/tamer/.npm-global/lib/node_modules/protractor/built/runner.js:198:43)
    at /home/tamer/.npm-global/lib/node_modules/protractor/built/runner.js:277:30
    at _fulfilled (/home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:834:54)
    at self.promiseDispatch.done (/home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:863:30)
    at Promise.promise.promiseDispatch (/home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:796:13)
    at /home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:556:49
    at runSingle (/home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:137:13)
    at flush (/home/tamer/.npm-global/lib/node_modules/protractor/node_modules/q/q.js:125:13)
    at nextTickCallbackWith0Args (node.js:420:9)
[15:23:48] E/launcher - Process exited with error code 135
tamer@tamer-Inspiron-N5110:/media/tamer/Work/conFusion/test$ sudo webdriver-manager update
[sudo] password for tamer: 
sudo: webdriver-manager: command not found

将错误传递给错误处理中间件,如例B中所示。

示例B

function(req, res, next)
{
    if (err) {
      err.message = 'Not Found';
      res.status(404).json(err);
      return;
    }
}

错误处理中间件:

function(req, res, next)
{
    if (err) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    }
}

1 个答案:

答案 0 :(得分:0)

想象一下,您正在通过多个函数来处理请求以处理它,并且其中一个函数中的错误是肤浅的。您仍然可以处理请求,但之后需要发送警告或处理错误。也许你想收集管道中的所有错误报告它们。例B允许这样做。

但是想象一下这个错误是至关重要的,你知道你无法继续下去。在这种情况下,您无法调用下一个,因为下一个函数不知道如何处理根本上破坏的请求。这是示例A派上用场的地方。