Wednesday 29 December 2021

ExpressJs send response with error inside middleware

I can't understand why my ExpressJs app is crashing sending res.status(401) inside a middleware.

Let's say my start.js has:

app.use(middlewares.timestampValidator());

and the middleware is declared as follow:

timestampValidator: () => {

return (req, res, next) => {

    [...]
    if(error) {
        res.status(401).json(new ServerResponse());
    }
    else {
        next();
    }
}
}

When the error is -successfully- sent to the client the server crashes with this error:

node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async > function without a catch block, or by rejecting a promise which was not handled with > > .catch(). The promise rejected with the reason "false".] { code: 'ERR_UNHANDLED_REJECTION' }

But the functions is not async. I tried calling next('error'); after sending status 401 but the app continues to routes and then the response can't be send to client because already sent.



from ExpressJs send response with error inside middleware

No comments:

Post a Comment