question: Erro "Cannot set headers after they are sent to the client" ao usar routing-controllers no Express
Opened this issue · 1 comments
marcoswebmasteroficial commented
I'm trying to configure my API with routing controllers in an Express project, but I'm having difficulty handling routes without issues (404) and general errors.
useExpressServer(app, {
controllers: [
path.join(__dirname, '..', 'controllers', `*.${fileExtension}`)
],
middlewares: [CustomErrorHandler],
defaultErrorHandler: false
})
app.use((req, res, next) => {
next(new NotFoundError('Rota não encontrada'))
})
And the
@Middleware({ type: 'after' })
export class CustomErrorHandler implements ExpressErrorMiddlewareInterface {
error(error: any, req: Request, res: Response, next: NextFunction): void {
if (res.headersSent) return
if (error.httpCode === 404) {
res.status(404).json({ message: 'Route not found' })
} else {
console.error('Erro:', error)
res.status(500).json({ message: 'Internal server error' })
}
}
}
The problem:
When I access a non-existent route (ex: /userss), I receive: Cannot set headers after they are sent to the client
attilaorosz commented
The problem is that the error handler must be the last defined middleware in express. Since you add an additional middleware at the end for 404, it will not trigger the error handler.
A workaround would be to define the error handler outside of routing-controllers either for all errors or just the 404.