skip to content

Exception Filters and Middleware

Exception filters turn uncaught errors into responses over the HttpException hierarchy; middleware binds via MiddlewareConsumer. Interviewers ask why only a global filter catches a middleware error.

on this pageshow

explore

questions

6

In NestJS 12, what response does the built-in exception filter send when a handler throws a NotFoundException, and when it throws a plain Error?

level: juniorimportance: must knowfreq 70%

answer

  1. one exceptions layer for the whole app
  2. a known hierarchy versus everything else
  3. statusCode and message in the body
  4. unknown means 500, and it gets logged

basics

~20 s

Nest's built-in global filter turns any HttpException, such as NotFoundException, into a JSON body with its status and message, here a 404. A plain Error outside that hierarchy becomes a logged 500 whose message is "Internal server error".

solid answer

~40 s

Nest catches every unhandled exception in its **exceptions layer**, and the built-in global filter knows one family: `HttpException` and its subclasses from `@nestjs/common`. `throw new NotFoundException()` becomes a 404 with `{"message":"Not Found","statusCode":404}`; passing a message, as in `new NotFoundException('Order 42 not found')`, adds an `error: "Not Found"` field beside it. If the first argument is an object, Nest sends that object as the whole body. Other errors, such as a plain `Error` or a `TypeError`, become `{"statusCode":500,"message":"Internal server error"}`, so their original message never leaks, and the filter logs it under `ExceptionsHandler`. `HttpException` itself is not logged, because it extends `IntrinsicException`, which the built-in filters treat as normal flow.

code

typescript · 14 lines
typescript
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';

@Controller('orders')
export class OrdersController {
  @Get(':id')
  findOne(@Param('id') id: string) {
    if (id === '42') {
      // 404 {"message":"Order 42 not found","error":"Not Found","statusCode":404}
      throw new NotFoundException(`Order ${id} not found`);
    }
    // 500 {"statusCode":500,"message":"Internal server error"}, logged by ExceptionsHandler
    throw new Error('orders table unreachable');
  }
}

go deeper

for a junior

Recall the two outcomes: an HttpException subclass gives its own status and a statusCode-plus-message body, anything else gives a generic 500. Name a few built-in subclasses and their codes.

for a middle

Explain how the first constructor argument shapes the body (string, object or nothing), why the error field appears only on the built-in subclasses, and that cause is never serialized.

for a senior

Show you know why a 500 hides the original message, why HttpException is not logged (IntrinsicException), and what that means for monitoring 4xx traffic in production.

for a principal

Discuss whether domain errors should extend HttpException or stay framework-free behind a mapping filter, and what each choice costs in coupling and in consistent client bodies.

## The exceptions layer Every NestJS application has an **exceptions layer**: when a route handler, a guard, a pipe, an interceptor or a middleware bound through Nest throws and nothing in your code catches it, the layer catches it and writes a response. Out of the box this is done by one **built-in global exception filter**. You do not register it; it is what answers when no filter of yours claims the exception. That filter sorts every exception into one of two groups: - **Recognized**: an instance of `HttpException` from `@nestjs/common`, or of any class that extends it. - **Unrecognized**: everything else, including a plain `Error`, a `TypeError` from a bug, or a domain error class of your own that does not extend `HttpException`. ## The HttpException hierarchy `HttpException` takes up to three constructor arguments: `response` (a string or an object), `status` (a number, best taken from the `HttpStatus` enum) and an optional `options` object. Nest ships about twenty ready-made subclasses that fix the status for you, among them: - `BadRequestException` (400), `UnauthorizedException` (401), `ForbiddenException` (403) - `NotFoundException` (404), `ConflictException` (409), `UnprocessableEntityException` (422) - `InternalServerErrorException` (500), `ServiceUnavailableException` (503), `GatewayTimeoutException` (504) A custom exception that extends `HttpException`, say an `OrderMissingException` that calls `super('Order missing', 404)`, is recognized the same way: the built-in filter checks the class with `instanceof`, so the whole subtree is covered. ## What the body looks like The body depends on what the first argument was. These are the bodies the Express adapter actually sends: | Thrown | Status | Body | |---|---|---| | `new NotFoundException()` | 404 | `{"message":"Not Found","statusCode":404}` | | `new NotFoundException('Order 42 not found')` | 404 | `{"message":"Order 42 not found","error":"Not Found","statusCode":404}` | | `new HttpException('Forbidden', HttpStatus.FORBIDDEN)` | 403 | `{"statusCode":403,"message":"Forbidden"}` | | `new HttpException({ code: 'X' }, 409)` | 409 | `{"code":"X"}` | | `new Error('db down')` | 500 | `{"statusCode":500,"message":"Internal server error"}` | Three rules explain the table: 1. A **string** first argument becomes `message`; the built-in subclasses also add an `error` field holding the status phrase (or the `description` you pass in the options). 2. An **object** first argument replaces the whole body; Nest serializes it as it is. 3. No first argument on a built-in subclass gives the bare `message` and `statusCode` pair. The `cause` option, used to chain the original error, is kept on the exception for logging and is never serialized into the body. ## Unrecognized errors become a 500 For almost anything outside the hierarchy the built-in filter answers **500** with the fixed message `Internal server error`. That is deliberate: the message of an arbitrary error may carry a SQL fragment, a file path or a stack detail, so the client sees only the generic text. The filter does partially understand a few foreign error shapes, notably errors built by the `http-errors` library (an `Error` carrying matching `status` and `statusCode` numbers and an `expose` flag), and sends their status and message instead of the generic 500. A domain `NotFoundError` that extends plain `Error` is therefore a 500 by default, not a 404. To get a 404 you either throw `NotFoundException` (or a subclass of `HttpException`) instead, or write an exception filter that maps the domain error. ## Logging and IntrinsicException The built-in filter **logs** unrecognized errors through Nest's `Logger` under the `ExceptionsHandler` context, with the stack, because a 500 usually means a bug. It does **not** log an `HttpException` of any status, not even a 500 thrown as `InternalServerErrorException`. The reason is in the class tree: `HttpException` extends `IntrinsicException`, and the built-in filters never log intrinsic exceptions, which they treat as part of normal application flow. If you want 4xx traffic or deliberate 500s in your logs, you add a custom exception filter that logs and then responds. ## Where this leaves you - Throw a built-in subclass when the status is the whole story. - Pass a message string for a readable reason, or an object when the client needs a specific body. - Expect a generic, logged 500 for everything else, and reach for a custom filter only when the default body or the default logging is not what you want.

  • In NestJS 12, what happens to the cause option you pass to an HttpException?
    It is stored on the exception's `cause` property so a logger or a custom filter can see the original error, but the built-in filter never serializes it into the response body. That makes `cause` the safe place for a database error you caught and rethrew as a `ServiceUnavailableException`.
  • Why does a thrown ForbiddenException never show up in a NestJS 12 application's error log?
    `ForbiddenException` extends `HttpException`, which extends `IntrinsicException`. The built-in exception filters never log intrinsic exceptions, because they are treated as expected application flow. To log them you bind a custom filter that writes the log line and then sends the response, or delegates to the base filter.
  • If a domain error class in a NestJS 12 app should always mean 404, what are the two usual ways to get that?
    Either make it part of the hierarchy, a class that extends `HttpException` or `NotFoundException`, so the built-in filter answers 404 by itself; or keep the domain class framework-free and write a filter decorated `@Catch(NotFoundError)` that sends the 404. The second keeps the domain layer free of HTTP types.

  • Says an uncaught Error in a handler crashes the Nest process.
  • Expects a plain Error's message to be returned to the client.
  • Believes HttpException responses are logged as errors by default.
  • Thinks a custom filter is required before HttpException produces JSON.
  • Assumes the cause option is serialized into the response body.
open as a page

In a NestJS 12 app, how do you bind a class middleware to some routes with MiddlewareConsumer, and when is functional middleware enough?

level: juniorimportance: must knowfreq 58%

basics

~10 s

Make the module implement NestModule and, in configure(consumer), call consumer.apply(TenantMiddleware).forRoutes(OrdersController), optionally with exclude() first. A plain function is enough when the middleware needs no injected dependencies.

open as a page

In NestJS 12, how do you write an exception filter with @Catch and ArgumentsHost that turns a domain NotFoundError into a 404 response?

level: middleimportance: must knowfreq 60%

basics

~10 s

Write a class implementing ExceptionFilter, decorate it @Catch(NotFoundError), and in catch(exception, host) call host.switchToHttp().getResponse() to send a 404 yourself. Bind it with @UseFilters on a handler or controller, or globally.

open as a page

In NestJS 12, how does registering a global exception filter with APP_FILTER differ from app.useGlobalFilters(), and when do you extend BaseExceptionFilter?

level: middleimportance: should knowfreq 45%

basics

~20 s

app.useGlobalFilters(new X()) builds the filter outside any module, so it gets no injected dependencies; an APP_FILTER provider is global too but Nest creates it with injection. Extend BaseExceptionFilter to add behaviour and still delegate to Nest's default response.

open as a page

In a NestJS 12 app, a tenant middleware throws UnauthorizedException, but the controller's @UseFilters filter never formats it. Why, and what fixes it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Consumer-bound middleware runs before Nest has selected a route handler, so only global exception filters apply to its errors; controller-scoped and method-scoped filters are never consulted. Register the formatting filter globally, through APP_FILTER or app.useGlobalFilters().

open as a page

In NestJS 12, what does the errorCode option on HttpException and its built-in subclasses put in the response, and how does it differ from cause?

level: middleimportance: nice to knowfreq 22%

basics

~10 s

In NestJS 12, errorCode is a stable string Nest adds to a string-message body as an errorCode field for clients to branch on; cause holds the original error for logging and is never serialized.

open as a page