htdangkhoa/pure-http

Custom error handler not being reached

zuavra opened this issue · 2 comments

zuavra commented

If I use the following app:

import pureHttp from 'pure-http';

const app = pureHttp();

app.get('/test',
    (req, res, next) => {
        throw new Error("bad");
    },
    (req, res, next) => {
        res.send("good");
    },
);

app.use((error, req, res, next) => {
    console.log('caught error', error);
});

app.listen(8000);

If I call localhost:8000/test I expect to get a console log with "caught error". Instead the default error handler catches the error and dumps it to the response.

What am I doing wrong?

zuavra commented

I've had a look at the router code. Unfortunately it looks like the middleware chain is being parsed linearly; custom error handlers are not on a separate error chain, they're on the main chain. This makes them position-sensitive and they only work in very particular circumstances:

  • If the router finds an error handler (middleware with 4 params) before there has been any error, it doesn't like it and stops with "Cannot GET /test". This means that if you put the custom error handler before the other middlewares they are never reached, effectively killing that route's handling (/test).
  • If the router finds a middleware after there's been an error but it's not an error handler (3 params instead of 4), it uses its default error handling, which is res.send(error.stack) to the client (because it also doesn't obey NODE_ENV=production to at least hide the errors on production). This means that if any regular middleware gets between the one that caused the error and the custom error handler, the custom error handler is never used.
  • The only way the custom error handler ever works is if it's placed directly after the middleware that causes the error... but since we cannot know in advance which middleware will cause an error, the only way it can work is to place an error handler after each and every middleware... which is not ideal.

hi @zuavra, sorry for the late reply. I confirm this issue exists, and have found a workaround. A patch will be released this week.

Once again I am very grateful for your contribution and feedback ❤️