CodePark/ questions / Exception filters
START PRACTICINGPRACTICE
Backend question · NestJS › Exception filters

How does Nest turn exceptions into HTTP responses by default? What happens with an HttpException versus a plain Error?

throw new NotFoundException("Cat not found");
// { "message": "Cat not found", "error": "Not Found", "statusCode": 404 }

throw new Error("db down");
// { "statusCode": 500, "message": "Internal server error" }

Nest has a built-in global exception filter. It catches any error that nothing else handled and turns it into a response.

An HttpException (or a subclass): Nest uses its status code and response body. Built-in subclasses include:

  • BadRequestException
  • UnauthorizedException
  • ForbiddenException
  • NotFoundException
  • ConflictException

They produce a JSON body with statusCode, message and error. You can also pass your own object as the body.

Any other error, like a plain Error: Nest treats it as unrecognised. The client gets a generic 500 with "Internal server error", so internal details don't leak. Nest logs the real error on the server.

So in services you have two choices. Throw HttpException subclasses directly. Or throw your own domain errors and translate them to HTTP with a custom filter.

  • A built-in global filter handles uncaught exceptions.
  • HttpException and its subclasses keep their status and body.
  • Unknown errors become a generic 500.
  • Built-in exceptions include NotFoundException, BadRequestException and others.