What if you could catch all errors in one place and never repeat error code again?
Why Exception filters in NestJS? - Purpose & Use Cases
Imagine building a NestJS app where every time an error happens, you manually check and handle it in each controller method.
You write repetitive try-catch blocks everywhere to catch errors and send responses.
This manual error handling is tiring and easy to forget.
It clutters your code and makes it hard to maintain or change error responses consistently.
Also, you risk missing some errors or sending inconsistent messages to users.
Exception filters in NestJS let you centralize error handling.
You write one filter to catch specific errors and format responses uniformly.
This keeps your controller code clean and your app's error responses consistent and easy to update.
try { // controller logic } catch (error) { if (error instanceof NotFoundError) { response.status(404).send('Not found'); } }
@Catch(NotFoundError) export class NotFoundFilter implements ExceptionFilter { catch(exception: NotFoundError, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(404).json({ message: 'Not found' }); } }
You can handle errors in one place and keep your app code clean and consistent.
When building an API, you want all 'not found' errors to return the same message and status code without repeating code in every route.
Manual error handling clutters code and risks inconsistency.
Exception filters centralize and simplify error responses.
This leads to cleaner, easier-to-maintain NestJS applications.
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
