Catching async errors from eval using domain

房东的猫 提交于 2019-12-24 11:41:21

问题


I'm trying to catch async errors with the npm eval module. It's very similar to the normal eval, except it utilizes node's vm module directly.

I just came across node's domain module. It allows me to catch async errors that occur within _eval.

However I checked the documentation and I can't find a done event for domain. How am I supposed to know when to resolve the promise?

var code = [
  "setTimeout(function () {",
  "  throw new Error('async error sim')",
  "}, 1000)"
].join('\n')

var domain = require('domain')
var _eval = require('eval')
var main = {}

var evalAsync = main.evalAsync = function (code, file) {
  return new Promise(function (resolve, reject) {
    var d = domain.create();
    d.on('error', function (e) {
      return reject(e)
    })
    var op = d.run(function () {
      return _eval(code, file, {}, true)
    })
    // return resolve(op)
  })
}

evalAsync(code, 'hi.js', {}, true)
  .catch(function (e) {
    console.log(e)
  })

Is there a way I can make the evalAsync module catch errors and return values correctly?

I've also tried this:

var op = d.run(function () {
  return _eval(code, file, {}, true)
})
return resolve(op)

来源:https://stackoverflow.com/questions/32195121/catching-async-errors-from-eval-using-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!