skip to content

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%

answer

  1. a class with one catch method
  2. the decorator names what it claims
  3. host gives back the platform objects
  4. switchToHttp, then getResponse
  5. bind by class for injection

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.

solid answer

~40 s

An exception filter is a class implementing `ExceptionFilter<T>` with one method, `catch(exception, host)`. `@Catch(NotFoundError)` from `@nestjs/common` records which exceptions it claims, matched with `instanceof`, so subclasses count; `@Catch()` with no arguments claims everything. `host` is an `ArgumentsHost`: `host.switchToHttp()` gives `getRequest()` and `getResponse()`, and on the Express adapter you call `response.status(404).json({...})`. Once a filter claims an exception, it owns the response: Nest calls no other filter and adds no default body, so a filter that sends nothing leaves the request hanging. Bind it with `@UseFilters(NotFoundErrorFilter)` on a handler or controller, preferably by class so Nest can inject its dependencies and reuse one instance.

code

typescript · 28 lines
typescript
import { ArgumentsHost, Catch, Controller, ExceptionFilter, Get, Param, UseFilters } from '@nestjs/common';
import type { Request, Response } from 'express';
import { NotFoundError } from './domain/errors.js';
import { OrdersService } from './orders.service.js';

@Catch(NotFoundError)
export class NotFoundErrorFilter implements ExceptionFilter<NotFoundError> {
  catch(exception: NotFoundError, host: ArgumentsHost) {
    const http = host.switchToHttp();
    const request = http.getRequest<Request>();
    http.getResponse<Response>().status(404).json({
      statusCode: 404,
      message: exception.message,
      path: request.url,
    });
  }
}

@Controller('orders')
@UseFilters(NotFoundErrorFilter)
export class OrdersController {
  constructor(private readonly orders: OrdersService) {}

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.orders.findOne(id); // may throw NotFoundError
  }
}

go deeper

for a junior

Recall the pieces: a class implementing ExceptionFilter, the @Catch decorator naming the type, the catch method, and @UseFilters to bind it.

for a middle

Explain instanceof matching, what ArgumentsHost hides across contexts, why only one filter answers, and the difference between binding by class and by instance.

for a senior

Show you can make a filter adapter-neutral, guard it with getType() in hybrid apps, and avoid filters that leave requests hanging or leak internal messages.

for a principal

Weigh mapping domain errors in filters against making domain errors extend HttpException, and decide how many filters a codebase should own before one shared mapping becomes clearer.

## What an exception filter is In NestJS an **exception filter** is a class that takes over the response for some exceptions. It implements the `ExceptionFilter<T>` interface from `@nestjs/common`, which asks for exactly one method: ```typescript catch(exception: T, host: ArgumentsHost): any; ``` Nest calls that method when an exception the filter claims reaches the exceptions layer. Whatever the method sends is the response; if it sends nothing, nothing is sent. The typical reason to write one is a **domain error** that should not know about HTTP. A repository throws `NotFoundError`, a plain class extending `Error`. Left alone, the built-in filter answers 500 for it, because it is not an `HttpException`. A filter can map it to 404 without the domain layer importing anything from Nest. ## @Catch: what the filter claims `@Catch()` is a class decorator that stores the exception types on the filter class: - `@Catch(NotFoundError)` claims `NotFoundError` and every subclass of it, because Nest matches with `instanceof`. - `@Catch(NotFoundError, ConflictError)` claims several types at once. - `@Catch()` with an empty list claims **every** exception, whatever its type, including `HttpException`. When several filters could apply to the same handler, Nest walks them in its own order, picks the first one whose types match and calls only that one. There is no fall-through to a second filter and no automatic default body afterwards. How Nest orders global, controller and route filters when looking for that match is a request-lifecycle topic; within one `@UseFilters(...)` list the docs advise listing a catch-everything filter first so a more specific one still wins. ## ArgumentsHost: reaching the request and response The second argument, `host`, is an `ArgumentsHost`. It wraps the arguments that were passed to the original handler in whatever context the request came from: | Method | Returns | |---|---| | `host.getType()` | `'http'`, `'rpc'` or `'ws'` | | `host.switchToHttp()` | an object with `getRequest()`, `getResponse()` and `getNext()` | | `host.switchToRpc()` / `host.switchToWs()` | the microservice or WebSocket equivalents | | `host.getArgs()` / `host.getArgByIndex(i)` | the raw argument array | On the default Express adapter, `getResponse()` returns the Express response, so `response.status(404).json(body)` works. On the Fastify adapter you call `response.send()` instead. A filter that must work on both can inject `HttpAdapterHost` from `@nestjs/core` and call `httpAdapter.reply(response, body, status)`. Do not confuse `host.switchToHttp().getResponse()` with `exception.getResponse()`: the second is a method of `HttpException` that returns the **body** you constructed the exception with, not the platform response object. ## A filter for the domain error The filter below maps `NotFoundError` to a 404 with the request path. Its steps: 1. Read the platform objects through `host.switchToHttp()`. 2. Build the body your clients expect. 3. Send it with the status you chose, and return. ```typescript @Catch(NotFoundError) export class NotFoundErrorFilter implements ExceptionFilter<NotFoundError> { catch(exception: NotFoundError, host: ArgumentsHost) { const http = host.switchToHttp(); const request = http.getRequest<Request>(); http.getResponse<Response>().status(404).json({ statusCode: 404, message: exception.message, path: request.url, }); } } ``` ## Binding the filter `@UseFilters()` binds filters to a single handler (method-scoped) or to every handler of a controller (controller-scoped). It accepts instances or classes: - `@UseFilters(new NotFoundErrorFilter())` works, but the instance is built by you, so it cannot receive injected providers. - `@UseFilters(NotFoundErrorFilter)` leaves instantiation to Nest, which enables dependency injection and lets Nest reuse one instance across the module. The docs recommend this form. For an application-wide filter there are two global registrations, `app.useGlobalFilters()` and the `APP_FILTER` provider token, which differ in whether the filter can inject dependencies. ## A filter or an HttpException subclass? There are two ways to make a domain failure come back as a 404, and they put the HTTP knowledge in different places: - **Throw an `HttpException` subclass** from the service, such as `NotFoundException`. No filter is needed, but the domain layer now imports `@nestjs/common` and decides HTTP statuses, which hurts if the same service also runs behind a message consumer or a CLI. - **Throw a plain domain error and map it in a filter.** The domain layer stays framework-free, and the mapping lives in one place at the edge. The cost is one more class, and a filter that must be bound wherever the error can surface, which is why such mapping filters often end up global. Neither is wrong; what matters is that a codebase picks one convention so clients see the same body for the same failure. ## Common mistakes - Expecting `@Catch(NotFoundError)` to see an error that a service already wrapped in a different class: matching is by the thrown object's class chain, not by its message. - Writing a filter that logs and returns without sending a response; the client waits until a timeout. - Using `response.json()` in a filter that also runs on Fastify. - Assuming a filter bound with `@UseFilters` on a controller also handles errors thrown by middleware; middleware errors reach only global filters.

  • In NestJS 12, how would you write the same filter so it works on both the Express and the Fastify adapter?
    Inject `HttpAdapterHost` from `@nestjs/core` into the filter's constructor, read `httpAdapter` from it inside `catch`, and send with `httpAdapter.reply(ctx.getResponse(), body, 404)` and `httpAdapter.getRequestUrl(ctx.getRequest())`. The adapter hides the difference between Express's `json()` and Fastify's `send()`. Bind such a filter by class or through `APP_FILTER` so the injection happens.
  • When should a NestJS 12 filter call host.getType() before switching context?
    When the same filter is bound where it can see HTTP requests and also microservice messages or WebSocket events, as a global filter in a hybrid app may. `getType()` returns `'http'`, `'rpc'` or `'ws'`, and calling `switchToHttp().getResponse()` on a message context gives you something that is not an HTTP response.

  • Thinks @Catch(NotFoundError) misses subclasses of NotFoundError.
  • Calls exception.getResponse() expecting the platform response object.
  • Expects Nest to fall back to the default body if the filter sends nothing.
  • Binds by instance and then wonders why injected services are undefined.
  • Believes an empty @Catch() catches nothing until types are listed.