davidbanham / express-async-errors

async/await support for ExpressJS
Other
900 stars 43 forks source link

Quite simple example is not working #6

Closed Alexsey closed 6 years ago

Alexsey commented 6 years ago

Consider code

const express = require('express')
require('express-async-errors')
const app = express()

app.get('/test', async (req, res) => {
    throw Error('custom message')
})

app.use((err, req, res, next) => {
    console.log('Catch error:', err.message)
    res.status(418)
    res.send('Error handled!')
});

app.listen(3000, () => console.log('Server started on 3000!'))

process.on('unhandledRejection', reason => {
    console.error('unhandledRejection:', reason)
})

would not send a respond and produce

...
unhandledRejection: Error: custom message
...

Am I doing something wrong?

Thank you

Alexsey commented 6 years ago

As I can see from

const Layer = require('express/lib/router/layer')
console.log(Layer.prototype)

there is no handle method but there are handle_error and handle_request

I have try to change the code for module to

Object.defineProperty(Layer.prototype, 'handle_request', {
  enumerable: true,
  get() { return this.__handle_request; },
  set(fn) {
    fn = wrap(fn);
    this.__handle_request = fn;
  }
});

Object.defineProperty(Layer.prototype, 'handle_error', {
  enumerable: true,
  get() { return this.__handle_error; },
  set(fn) {
    fn = wrapErrorMiddleware(fn);
    this.__handle_error = fn;
  }
});

but it didn't work. Probably the way to monkey should also change some way

Alexsey commented 6 years ago

It appears I was using express 4.15.2. I have switched to 4.16.2 and now everything works

davidbanham commented 6 years ago

Glad to hear you got it figured out, Alexsey! Even though it wasn't needed in the end, thanks for such a well written reproduction case.

ccorcos commented 6 years ago

Oh wow. Doesnt work on 4.16.0 either, but works on 4.16.2