node.js – Express应用程序中的未处理拒绝

我有很多基于ES6承诺的代码运行在我的快速应用程序。如果有一个错误,从来没有抓到我使用下面的代码来处理它:

process.on('unhandledRejection',function(reason,p) {
  console.log("Unhandled Rejection:",reason.stack);
  process.exit(1);
});

这适用于调试目的。

但在生产中,我想触发500错误处理程序,向用户显示标准“出了问题”页面我有这个catch所有的错误处理程序,目前适用于其他异常:

app.use(function(error,req,res,next) {
  res.status(500);
  res.render('500');
});

将unhandledRejection放在中间件内部不工作,因为它的异步和offen导致错误:无法渲染头后,他们发送到客户端。

如何在未处理的拒绝中呈现500页面

解决方法

Putting the unhandledRejection inside a middleware…often results in a Error: Can't render headers after they are sent to the client.

对您的错误处理程序稍作更改:

// production error handler
const HTTP_SERVER_ERROR = 500;
app.use(function(err,next) {
  if (res.headeRSSent) {
    return next(err);
  }

  return res.status(err.status || HTTP_SERVER_ERROR).render('500');
});

ExpressJS Documentation

Express comes with an in-built error handler,which takes care of any errors that might be encountered in the app. This default error-handling middleware is added at the end of the middleware stack.

If you pass an error to next() and you do not handle it in an error handler,it will be handled by the built-in error handler – the error will be written to the client with the stack trace. The stack trace is not included in the production environment.

Set the environment variable NODE_ENV to “production”,to run the app in production mode.

    如果在开始写响应后调用next()时出现错误,例如,如果在将响应流式传输到客户端时遇到错误,则Express’default错误处理程序将关闭连接并使请求被视为失败。    因此,当您添加自定义错误处理程序时,您将希望委派到express中的错误处理机制,当头已经发送到客户端。

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...