ExceptionFilter

Interface for filters that catch unhandled exceptions and craft the response.

Since NestJS 10/11 Spec ↗

Syntax

catch(exception: T, host: ArgumentsHost): void

Parameters

NameTypeRequiredDescription
exception T No The thrown exception instance.
host ArgumentsHost No Accessor for the request and response objects.

Returns

void — The filter writes the response itself.

Examples

import {
  ExceptionFilter, Catch, ArgumentsHost, HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse();
    const status = exception.getStatus();
    res.status(status).json({
      statusCode: status,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}

Notes

Annotate the class with @Catch() to choose which exceptions it handles. The filter is responsible for sending the response. Bind it with @UseFilters() or app.useGlobalFilters().