【问题标题】:How does exactly Express.js handle errors?Express.js 究竟是如何处理错误的?
【发布时间】:2018-01-04 04:46:22
【问题描述】:

所以,微不足道的事情。我们都知道 Express 有内置的默认错误处理程序,它需要四个参数(err、req、res、next)来处理“同步异常”,如 ReferenceError、TypeError 等:

更新: 这个问题是 Express 特有的,而不是关于如何捕获未处理的异常/等。我想知道 Express 在第一个代码块中如何处理用户定义的异常。异步的第二个例子。异常不直接属于这个问题。

const express = require('express')();

express.all('*', (req, res) => {
  throw new Error('my own error');
  res 
    .send('okay?');
});

express.use((err, req, res, next) => {
  console.error(err.stack);
  res 
    .status(503)
    .send('Express is still up and running');
}).listen(3000);

但不是这个:

const express = require('express')();

express.all('*', (req, res) => {
  process.nextTick(() => {
    throw new Error('my own error');
  });
  res 
    .send('okay?');
});

express.use((err, req, res, next) => {
  console.error(err.stack);
  res 
    .status(503)
    .send('Won\'t be executed');
}).listen(3000);

但是我很好奇这个处理程序的实现。

我找不到类似的东西

process.on('uncaughtException'... 或域/Promises/cluster。

也许我错过了什么。

谁能澄清一下?

【问题讨论】:

    标签: node.js express error-handling try-catch


    【解决方案1】:

    有一个catch-all kind of block in Express's router 被执行:

    try {
      fn(req, res, next);
    } catch (err) {
      next(err);
    }
    

    因此,在此块中,所有异常都被捕获并转换为 next() 函数调用,并设置了错误参数以匹配异常。

    更详细地说,当一个请求到达时要表达:

    • 调用app.handle(),然后确定路由器并调用router.handle()
    • router.handle() 逐层处理并最终匹配您使用express.all('*', ...) 签名注册的处理程序
    • handle_request(在路由器的内部 Layer 模块内)调用您在上述 try-catch 块中指定的处理函数,有效地捕获所有可能的异常并将它们转换为下一个调用。

    【讨论】:

    • 感谢您的详细解答。我刚刚制作了自己的“Express”来重现这种行为。对我来说非常简单优雅的处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多