In NestJS 12, how does registering a global exception filter with APP_FILTER differ from app.useGlobalFilters(), and when do you extend BaseExceptionFilter?
answer
- inside a module or outside it
- who gets dependency injection
- gateways and hybrid apps
- super.catch keeps the default body
basics
~20 sapp.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.
solid answer
~40 sBoth make a filter apply to every route. `app.useGlobalFilters(new AllExceptionsFilter())` in `main.ts` takes an instance you build, outside any module, so it cannot inject a logger or a config service, and the docs warn it does not set up filters for gateways or hybrid applications. A provider `{ provide: APP_FILTER, useClass: AllExceptionsFilter }` from `@nestjs/core` is created by the container, so constructor injection works, and the filter is global whichever module declares it. `BaseExceptionFilter` is the class behind Nest's default response: extend it when you want to log, or map one error type, and then call `super.catch(exception, host)` to send the usual body. It needs the HTTP adapter, which `APP_FILTER` injects for you; with `useGlobalFilters` you pass `app.get(HttpAdapterHost).httpAdapter` to its constructor.
code
typescript · 18 linesimport { ArgumentsHost, Catch, Module, NotFoundException } from '@nestjs/common';
import { APP_FILTER, BaseExceptionFilter } from '@nestjs/core';
import { NotFoundError } from './domain/errors.js';
@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
if (exception instanceof NotFoundError) {
return super.catch(new NotFoundException(exception.message), host);
}
super.catch(exception, host);
}
}
@Module({
providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }],
})
export class AppModule {}go deeper
Recall that both registrations make a filter global, and that APP_FILTER lives in a module's providers while useGlobalFilters() is called in main.ts.
Explain why only the APP_FILTER form gets dependency injection, what BaseExceptionFilter's catch() does by default, and how it gets its HTTP adapter in each registration.
Show you would keep one injected global filter that logs and delegates with super.catch, and know the gateway and hybrid-app warning on useGlobalFilters().
Decide what a team's single global filter must do (logging, correlation ids, domain mapping) and what stays in local filters, so client bodies stay consistent across modules.
## Two ways to make a filter global A **global** exception filter applies to every controller and every route handler in a NestJS application. Nest offers two registrations for it, and they differ in who builds the filter. | | `app.useGlobalFilters(new X())` | `{ provide: APP_FILTER, useClass: X }` | |---|---|---| | Where | `main.ts`, on the application instance | the `providers` of any module | | Who instantiates | you, with `new` | the DI container | | Constructor injection | no | yes | | Scope | global | global, regardless of the declaring module | `useGlobalFilters()` is declared as `useGlobalFilters(...filters: ExceptionFilter[])`: it takes instances. Because they are created outside the context of any module, the docs state plainly that such filters cannot inject dependencies. That is fine for a filter that only reshapes the body; it is a problem the moment the filter needs a logger service, a metrics client or configuration. The docs also warn that `useGlobalFilters()` does not set up filters for gateways or hybrid applications; and in a hybrid app, the microservice side does not inherit global filters from either registration unless it is connected with `inheritAppConfig`, a detail of the microservices material. `APP_FILTER` is an injection token exported from `@nestjs/core`. Listing it as a provider tells Nest to create the class through the container and add it to the global filters: ```typescript @Module({ providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }], }) export class AppModule {} ``` Points worth remembering: - The filter is global **regardless of the module** that declares it; the docs suggest declaring it in the module where the filter class lives. - You can list several `APP_FILTER` providers. - `useClass` is not the only option: any custom provider form works. - A class decorated with `@Catch()` does not belong in `imports`; Nest's own error message says to move it to `providers` with `APP_FILTER`, or apply it with `@UseFilters()`. ## BaseExceptionFilter: extending the default instead of replacing it A custom filter normally owns the whole response. Often you only want to **add** something: log every exception with a request id, count failures, or map one domain error to a different status, and otherwise keep Nest's usual bodies. For that, `@nestjs/core` exports `BaseExceptionFilter`, the class that implements the default behaviour. Its `catch()` does what the built-in filter does: 1. An `HttpException` is answered with its status and its body (`statusCode` and `message` for a string, the object itself for an object). 2. Anything else becomes `{"statusCode":500,"message":"Internal server error"}` and is logged under `ExceptionsHandler`. 3. If headers were already sent, it ends the response instead of writing a body. You extend it, decorate the subclass `@Catch()`, do your own work, and call `super.catch(exception, host)`: ```typescript @Catch() export class AllExceptionsFilter extends BaseExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { if (exception instanceof NotFoundError) { return super.catch(new NotFoundException(exception.message), host); } super.catch(exception, host); } } ``` With this filter a domain `NotFoundError` comes back as `{"message":"Order 42 not found","error":"Not Found","statusCode":404}`, and every other exception keeps exactly the default response. ## Giving BaseExceptionFilter its HTTP adapter `BaseExceptionFilter` writes the response through the HTTP adapter, so it must get one: - **Through `APP_FILTER`**: the container injects `HttpAdapterHost` into it, and nothing else is needed. - **Through `useGlobalFilters`**: pass the adapter yourself, `const { httpAdapter } = app.get(HttpAdapterHost); app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));`. - **At method or controller scope**: the docs warn that filters extending `BaseExceptionFilter` should not be instantiated with `new` there; bind them by class with `@UseFilters(AllExceptionsFilter)` so Nest instantiates them. ## Adding logging without losing the default A frequent reason to write such a filter is that the built-in filter logs only unrecognized errors; `HttpException` instances, 4xx or not, are never logged because they extend `IntrinsicException`. A global filter registered through `APP_FILTER` can inject a logger and still answer exactly as before: 1. Decorate it `@Catch()` so it sees every exception. 2. Write the log line it needs, for example the status, the path and a request id. 3. Call `super.catch(exception, host)` so the response, the headers-sent check and the logging of unknown errors stay as Nest does them. Because the filter claims every exception, Nest does not fall back to the built-in filter afterwards; the `super.catch()` call is what keeps the default behaviour. ## Choosing - Use `APP_FILTER` by default for a global filter: it gets injection, and it is declared in a module like other providers. - Keep `useGlobalFilters()` for a dependency-free filter you want visible in `main.ts`, remembering the gateway and hybrid-app warning. - Extend `BaseExceptionFilter` when your filter adds to the default behaviour; write a plain `ExceptionFilter` when it replaces the body entirely.
- In NestJS 12, how do you register a filter extending BaseExceptionFilter with app.useGlobalFilters()?Get the adapter from the application and pass it to the constructor: `const { httpAdapter } = app.get(HttpAdapterHost); app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));`. `BaseExceptionFilter` writes responses through that adapter, and an instance you build with `new` is not injected, so it would otherwise have none.
- In NestJS 12, why might a team keep one global filter extending BaseExceptionFilter instead of several replacement filters?Because `super.catch()` keeps Nest's default bodies, status handling, the headers-sent check and the logging of unrecognized errors. A filter that only adds a log line or one mapping stays small, and every exception it does not care about still gets exactly the response clients already expect.
- Thinks app.useGlobalFilters() filters can use constructor injection.
- Believes an APP_FILTER provider applies only to its own module.
- Puts a @Catch() filter class in a module's imports array.
- Instantiates a BaseExceptionFilter subclass with new at controller scope.
- Assumes extending BaseExceptionFilter replaces the default body entirely.