微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中的错误处理机制,当头已经发送到客户端。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐