try/catch有局限-uncaughtException事件倒挂process对象上捕获异步回调里的异常

  1. process.on('uncaughtException', function (error) {
  2. //
  3. })
  4. process.nextTick(function () {
  5. fs.readFile('/index.js', function (error, str) {
  6. if (error) throw error;
  7. })
  8. })

domain模块(nodejs内置模块)

写法1:run是对enter/exit的简单封装

  1. const domain = require('domain');
  2. let d = d.create();
  3. d.on('error', function(error) {})
  4. d.run(function() {
  5. // TODO
  6. })

写法2:enter+exit (有限制: 不便处理多个domain混合、嵌套)

  1. d.enter();
  2. // TODO
  3. d.exit();

d.bind()
d.intercept()