02 / 03

What is an exception filter in NestJS and when does it run?

An exception filter catches unhandled exceptions thrown anywhere in the request pipeline — middleware, guards, interceptors, pipes, or the handler itself — and converts them into an HTTP response. The @Catch() decorator specifies which exception type(s) to intercept. Omitting it catches everything.

HttpException filter implementation
Exception filter key facts:
  1. 1

    @Catch(HttpException) — only handles HttpException and its subclasses.

  2. 2

    @Catch() with no argument — catches every exception including non-HTTP errors.

  3. 3

    @Catch(NotFoundException, BadRequestException) — handles multiple types.

  4. 4

    host.switchToHttp() provides access to req and res objects.

  5. 5

    exception.getResponse() returns either a string or an object depending on how the exception was thrown.