skip to content

In a NestJS 12 app with route, controller and global exception filters, which one handles a thrown exception, and why does the closest filter not always win?

level: seniorimportance: should knowfreq 45%

answer

  1. the one component not global-first
  2. first matching @Catch() wins
  3. no hand-off between filters
  4. a guard's error stays in the route

basics

~20 s

Nest checks route filters, then controller filters, then global ones, and the first whose @Catch() matches the exception, or is empty, handles it alone. A closer filter wins only when its @Catch() matches, and no filter hands the exception on.

solid answer

~40 s

Filters are the one component that does not resolve global first. For a route, Nest builds the list global, controller, route and then reverses it, and picks the first filter whose `@Catch()` types match the exception by `instanceof`, or that has no types at all. Nest calls exactly one filter; there is no passing the exception on to an outer filter, so shared behaviour comes from inheritance, for example extending `BaseExceptionFilter`. If nothing matches, Nest's built-in filter answers, with `500` and `Internal server error` for a plain `Error`. Where the exception is thrown also matters: a guard's `ForbiddenException` is thrown inside the route and reaches route and controller filters, while a path no route matches never selects one, so only global filters see its `NotFoundException`.

code

typescript · 32 lines
typescript
@Catch(NotFoundException)
export class ReportMissingFilter implements ExceptionFilter {
  catch(exception: NotFoundException, host: ArgumentsHost) {
    host.switchToHttp().getResponse().status(404).json({ reason: 'report-missing' });
  }
}

@Catch(HttpException)
export class ReportsHttpFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    host.switchToHttp().getResponse().status(exception.getStatus()).json({ reason: 'reports-http' });
  }
}

@Catch()
export class LastResortFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    host.switchToHttp().getResponse().status(500).json({ reason: 'last-resort' });
  }
}

@UseFilters(ReportsHttpFilter)
@Controller('reports')
export class ReportsController {
  @UseFilters(ReportMissingFilter)
  @Get(':id')
  find(@Param('id') id: string) {
    throw new TypeError('cannot read the report row');
  }
}

// app.module.ts: providers: [{ provide: APP_FILTER, useClass: LastResortFilter }]

go deeper

for a junior

Know that exception filters are the one component resolved route first, and that only one filter handles a given exception.

for a middle

Explain how @Catch() types and instanceof decide the match, and why a catch-everything filter must be listed first within one @UseFilters().

for a senior

Diagnose a filter that never fires: an unmatched path that only global filters see, a closer filter that matched first, or a try/catch that swallowed it.

for a principal

Set a filter policy that survives these rules: one global filter as the error contract, few scoped filters, and shared behaviour through BaseExceptionFilter inheritance.

## Route first, then controller, then global Every other kind of **NestJS** component runs global, then controller, then route. **Exception filters** are the exception. Nest checks **route-bound filters first, then controller-level filters, and finally global filters**. In the v12.1.2 source the router builds the usual global, controller, route list and then reverses it before storing it on the route's exceptions handler. Selection is a search, not a cascade: 1. Nest walks the reversed list. 2. A filter **matches** when its `@Catch()` decorator lists no types (a catch-everything filter), or when the exception is an `instanceof` one of the listed types. 3. The **first** matching filter's `catch(exception, host)` is called, and the search stops. 4. If no custom filter matches, Nest's built-in global filter handles it. Two consequences: - **A closer filter does not win unless it matches.** A route filter decorated `@Catch(NotFoundException)` ignores a `TypeError`; the search moves on to the controller and then to the global filters. - **Exceptions cannot be passed from filter to filter.** Once a route-level filter catches an exception, no controller or global filter sees it. To share behaviour, use inheritance: extend a common filter class, or extend `BaseExceptionFilter` and call `super.catch()` for the cases you do not handle. ## Order inside one binding The reversal also applies inside one `@UseFilters()` list, and inside the global list. With `@UseFilters(CatchAllFilter, NotFoundFilter)`, `NotFoundFilter` is checked first. That is why the docs warn: when combining a catch-everything filter with one bound to a specific exception type, **declare the catch-everything filter first**, so the more specific one can still handle its type. ## Where the exception was thrown matters Filters bound with `@UseFilters()` belong to a route or controller, so they only apply once Nest is inside that route's context: - **Guards, interceptors, pipes and the handler** run inside the route context, so route and controller filters apply. When a guard returns `false`, the `ForbiddenException` Nest throws is caught by a controller filter that matches `HttpException`. - **An unmatched path** never selects a route, so its `NotFoundException` (message `Cannot GET /path`) reaches only global filters. ## Reading the worked example The code example binds `@Catch(NotFoundException)` on one route, `@Catch(HttpException)` on the controller and a catch-everything `@Catch()` globally through `APP_FILTER`. The outcome table shows which filter answers each case: | Thrown | Where | Handled by | |---|---|---| | `NotFoundException` | handler | the route filter | | `BadRequestException` | handler or a pipe | the controller filter (`HttpException` matches) | | `TypeError` | handler | the global filter (neither closer filter matches) | | `ForbiddenException` from a guard | guard | the controller filter | ## When nothing matches If no custom filter matches, Nest's built-in exception filter answers: - For an `HttpException` (or a subclass such as `NotFoundException`), it sends the exception's response: by default a JSON body with `statusCode` and `message`. - For a plain `Error` or any other unrecognised value, it replies `500` with `{"statusCode":500,"message":"Internal server error"}` and logs the error. The same reversal applies to the global list itself: filters added with `app.useGlobalFilters()` in `main.ts` join the list after the `APP_FILTER` providers applied during bootstrap, so after the reversal they are checked **before** them. Two catch-everything global filters registered in the two styles therefore do not both run; the `useGlobalFilters()` one answers. ## How to diagnose a filter that never fires - Check **where** the exception is thrown: an unmatched path never selects a route, so only global filters see it. - Check whether a **closer filter matched first**: a controller filter on `HttpException` will swallow every HTTP exception before a global one sees it. - Check the **order inside one `@UseFilters()`** list: a catch-everything filter listed last is checked first and hides the specific one. - Check whether the code **caught the exception itself**: an exception you catch with `try/catch` never reaches a filter.

  • In a NestJS 12 app, how do you let a route filter handle a few cases and leave the rest to the default behaviour?
    Extend `BaseExceptionFilter`, handle the cases you care about, and call `super.catch(exception, host)` for the others. Filters cannot hand an exception to an outer filter, so inheritance is the documented way to reuse behaviour across levels.
  • In a NestJS 12 app, why is the global filter, not the controller filter, answering a request for a path that does not exist?
    An unmatched path never selects a route, so no controller or method filters are attached to it. Nest raises a `NotFoundException` with a message such as `Cannot GET /nope`, and only global filters apply.
  • In a NestJS 12 app, a guard returns false; which filters can handle the resulting error?
    All of them, route first. Guards run inside the route's context, so the `ForbiddenException` Nest throws is resolved like a handler's error: a route filter, then a controller filter matching `HttpException`, then global filters.

  • Global filters are checked first, as with guards and pipes.
  • A route filter catches every exception thrown on that route.
  • After a route filter handles an error, the global filter also runs.
  • A guard's ForbiddenException skips controller filters and goes straight to global ones.
  • In @UseFilters(A, B), filter A is always checked first.