Exception filters help you catch and handle errors in your NestJS app in one place. They make your app respond nicely when something goes wrong.
Exception filters in NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; @Catch(HttpException) export class MyExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, custom: 'This is a custom error message', }); } }
The @Catch() decorator tells NestJS which errors this filter handles.
The catch() method runs when an error happens and lets you customize the response.
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common'; @Catch() export class AllExceptionsFilter implements ExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(500).json({ statusCode: 500, message: 'Something went wrong', }); } }
import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common'; @Catch(NotFoundException) export class NotFoundFilter implements ExceptionFilter { catch(exception: NotFoundException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: 'Resource not found', }); } }
This example shows a controller with a route that throws an error. The custom exception filter catches it and sends a JSON response with the error details and a timestamp.
import { Controller, Get, UseFilters, HttpException, HttpStatus } from '@nestjs/common'; import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common'; @Catch(HttpException) class CustomHttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message || 'Default error message', timestamp: new Date().toISOString(), }); } } @Controller('test') @UseFilters(CustomHttpExceptionFilter) export class TestController { @Get('error') throwError() { throw new HttpException('Custom error happened', HttpStatus.BAD_REQUEST); } }
Exception filters only catch errors thrown inside the route handlers or services called by them.
You can create filters for specific error types or catch all errors by leaving @Catch() empty.
Use ArgumentsHost to access request and response objects to customize responses.
Exception filters help handle errors in one place and send custom responses.
Use @Catch() to specify which errors to catch.
Filters keep your code clean and improve user experience by controlling error messages.
Practice
Solution
Step 1: Understand what exception filters do
Exception filters catch errors thrown during request handling and allow custom responses.Step 2: Compare with other options
Options B, C, and D relate to other NestJS features, not error handling.Final Answer:
To catch and handle errors in a centralized way -> Option AQuick Check:
Exception filters = centralized error handling [OK]
- Confusing exception filters with middleware
- Thinking filters manage routes or database
- Assuming filters handle authentication
Solution
Step 1: Recall the decorator for exception filters
The correct decorator to mark a class as an exception filter is @Catch().Step 2: Verify other decorators
@Exception(), @Filter(), and @ErrorHandler() are not valid NestJS decorators for filters.Final Answer:
@Catch() -> Option BQuick Check:
@Catch() marks exception filters [OK]
- Using @Exception() instead of @Catch()
- Confusing with @Filter() which is not a decorator
- Assuming @ErrorHandler() exists in NestJS
import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common';
@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
catch(exception: NotFoundException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(404).json({ message: 'Resource not found' });
}
}Solution
Step 1: Analyze the response status set in the filter
The filter explicitly sets the status code to 404 using response.status(404).Step 2: Understand the exception type caught
The filter catches NotFoundException, which corresponds to HTTP 404 errors.Final Answer:
404 -> Option AQuick Check:
NotFoundException triggers 404 status [OK]
- Assuming default 500 status without custom filter
- Confusing 404 with 400 or 200
- Ignoring the status set in the filter
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(500).json({ message: exception.message });
}
}Solution
Step 1: Check the @Catch() decorator usage
The @Catch(HttpException) references HttpException, but it is not imported from '@nestjs/common'.Step 2: Validate other parts
catch method can omit return type and exception type in loose TS, exception.message is valid.Final Answer:
Not importing HttpException class -> Option DQuick Check:
Import HttpException for @Catch(HttpException) [OK]
- Not importing referenced exception types like HttpException
- Assuming catch method needs strict return type
- Thinking exception needs getMessage() method
Solution
Step 1: Recall how to apply global filters in NestJS
Global filters are applied using app.useGlobalFilters() method in the main bootstrap file.Step 2: Evaluate other options
@Global() is for modules, not filters; registering in providers is local; app.setGlobalExceptionFilter() does not exist.Final Answer:
Use app.useGlobalFilters(new YourFilter()) in main.ts after creating the filter class -> Option CQuick Check:
Global filters use app.useGlobalFilters() [OK]
- Using @Global() decorator on filter class
- Registering filter only in providers without global call
- Assuming app.setGlobalExceptionFilter() exists
Ready to prove it?
Pass the test and this pattern moves unknown
