表达错误或域错误? [英] Express error handling or domain?

查看:90
本文介绍了表达错误或域错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在nodejs中构建一个应用程序并进行表达.谁能帮助我了解以下代码段之间的区别:

I am building an app in nodejs and express. Can anybody help me to understand the difference between the following pieces of code:

  var app = express();
  app.use(function(err, req, res, next){
  console.error(err);
  res.render('home.ejs', {message:'Something broke!'});
  });

 var domain = require('domain');
 var d = domain.create();
 d.on('error', function(err) {
 console.error(err);
 res.render('home.ejs', {message:'Something broke!'});
 });

这两段代码是否可以替代?如果可以,为了避免应用程序在生产时崩溃,哪个更可靠?

Are the two pieces of code alternative? If yes, which one is more reliable in order to avoid the app crashing on production?

推荐答案

Express在try/catch中包装每个function (req, res, next) {}.捕获许多错误,但不捕获异步错误.域捕获异步错误.但是,捕获错误并进行处理是两个不同的事情.

Express wraps each function (req, res, next) {} in a try/catch. Which catches many errors, but not async errors. Domains catch async errors. However catching the error and handling it are two different things.

如果您接下来遇到错误(也称为d.on('error', next);),则最终将要表达错误中间件,就像在第一个示例中一样.

If you next the error (aka d.on('error', next);) it will end up in going to express error middleware, just like in your first example.

因此,与其考虑快递与域名,不如考虑try/catch与域名.无论哪种情况,都应使用Express处理错误.

So instead of thinking about express vs domains, think try/catch vs domains. Express should be used to handle the error in either case.

这篇关于表达错误或域错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆