Endpoint Error Handling

If anyone is using RunKit’s to create endpoints and finding the error handling less than satisfactory, with a lot of cases of exceptions resulting in timeouts or an opaque { "error": "unexpected_error", ... } being returned rather than returning useful error messages with information about the error and stacktrace, I’ve found a workaround where I manually use Domains to catch the errors:

function endpoint (req, res) {
    // do your thing
}

const domain = require('domain')
exports.endpoint = function (req, res) {
    const d = domain.create()
    d.on('error', function (e) {
        res.statusCode = 500
        res.end(`${e.stack}\n`)
    })
    d.add(req)
    d.add(res)
    d.run(endpoint, req, res)
}

For more about RunKit’s faulty use of Domains and why this workaround has to do the things it does, see: https://runkit.com/laughinghan/58337152a62a08001304609a

One thing I am extremely confused about: somehow, in the following, the error is caught by RunKit rather than my manual error catcher, which is quite contrary to my understanding of how domains work.

const domain = require('domain')
exports.endpoint = function (req, res) {
    domain.create()
    .on('error', function (e) {
      res.statusCode = 500
      res.end(`Manually caught error:\n${e.stack}\n`)
    })
    .run(() => fail)
}

Try it here: https://runkit.io/laughinghan/58337152a62a08001304609a/branches/master/surprising_caught_error

Anyone know why My error catcher is not returned by that?