01 / 03

How do you write a global filter in NestJS that handles both HttpException and unexpected errors differently?

Use @Catch() with no argument to catch all exceptions. Branch on instanceof HttpException — known HTTP exceptions are passed through with their status and message, while unknown errors are logged in full but return a generic 500 to the client. This two-branch pattern is the production standard.

Global all-exceptions filter with two branches
Production error handling best practices:
  1. 1

    Always log the full error including stack trace for unexpected errors.

  2. 2

    Never expose internal error details (stack traces, DB errors) to the client.

  3. 3

    HTTP exceptions are expected client errors — surface their message and status.

  4. 4

    Unknown errors should always return 500 with a generic message.

  5. 5

    Include the request path in error responses to help with client-side debugging.