0
0
NestJSframework~30 mins

Global exception filters in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Global Exception Filters in NestJS
📖 Scenario: You are building a simple NestJS API that needs to handle errors globally. Instead of writing try-catch blocks in every controller, you want to create a global exception filter that catches all exceptions and returns a consistent error response.
🎯 Goal: Create a global exception filter in NestJS that catches all exceptions and returns a JSON response with statusCode, timestamp, and message. Apply this filter globally to your application.
📋 What You'll Learn
Create a class called AllExceptionsFilter that implements ExceptionFilter
Use the @Catch() decorator without arguments to catch all exceptions
In the catch method, extract the HttpException status code or default to 500
Return a JSON response with statusCode, timestamp, and message
Apply the AllExceptionsFilter globally in the main.ts file using app.useGlobalFilters()
💡 Why This Matters
🌍 Real World
Global exception filters help keep error handling consistent and clean in real-world NestJS APIs by avoiding repetitive try-catch blocks.
💼 Career
Understanding global exception filters is important for backend developers working with NestJS to build robust and maintainable APIs.
Progress0 / 4 steps
1
Create the AllExceptionsFilter class
Create a class called AllExceptionsFilter that implements ExceptionFilter. Use the @Catch() decorator without arguments. Inside, define a catch(exception: unknown, host: ArgumentsHost) method.
NestJS
Need a hint?

Use @Catch() with no arguments to catch all exceptions.

2
Extract status code and response object
Inside the catch method of AllExceptionsFilter, get the HttpArgumentsHost from host.switchToHttp(). Extract response and request from it. Also, determine the status code by checking if exception is an instance of HttpException. If yes, get the status with exception.getStatus(), otherwise set it to 500.
NestJS
Need a hint?

Use host.switchToHttp() to get HTTP context, then get response and request.

Use instanceof HttpException to check exception type.

3
Send JSON error response
Still inside the catch method, use response.status(status).json() to send a JSON object with these keys: statusCode set to status, timestamp set to new Date().toISOString(), and message set to exception.message if exception is an HttpException, otherwise set it to 'Internal server error'.
NestJS
Need a hint?

Use response.status(status).json({ ... }) to send the error details.

4
Apply the filter globally in main.ts
In main.ts, import AllExceptionsFilter and apply it globally by calling app.useGlobalFilters(new AllExceptionsFilter()) before await app.listen(). Assume app is the NestJS application instance.
NestJS
Need a hint?

Use app.useGlobalFilters(new AllExceptionsFilter()) to apply the filter globally.