Skip to content

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

Open
@marcoswebmasteroficial

Description

@marcoswebmasteroficial

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions