Skip to content

question: Erro "Cannot set headers after they are sent to the client" ao usar routing-controllers no Express #1510

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
marcoswebmasteroficial opened this issue May 5, 2025 · 1 comment
Labels
type: question Questions about the usage of the library.

Comments

@marcoswebmasteroficial
Copy link

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

@marcoswebmasteroficial marcoswebmasteroficial added the type: question Questions about the usage of the library. label May 5, 2025
@attilaorosz
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

2 participants