Open
Description
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