📖 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
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
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
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
Hint
Use app.useGlobalFilters(new AllExceptionsFilter()) to apply the filter globally.
Practice
(1/5)
1. What is the main purpose of a global exception filter in a NestJS application?
easy
A. To catch and handle exceptions across the entire application in one place
B. To define routes for the application
C. To manage database connections
D. To serve static files
Solution
Step 1: Understand the role of exception filters
Exception filters in NestJS are designed to catch errors and exceptions that occur during request processing.
Step 2: Identify the scope of global exception filters
Global exception filters apply this error handling across the entire app, centralizing error management.
Final Answer:
To catch and handle exceptions across the entire application in one place -> Option A
Quick Check:
Global exception filters = app-wide error handling [OK]
Hint: Global filters catch errors everywhere in the app [OK]
Common Mistakes:
Confusing filters with routing or database management
Thinking filters serve static files
Assuming filters only handle specific routes
2. Which of the following is the correct way to apply a global exception filter in the main.ts file of a NestJS app?
easy
A. app.useGlobalFilters(new MyExceptionFilter())
B. app.setGlobalFilters(new MyExceptionFilter())
C. app.applyGlobalFilters(MyExceptionFilter)
D. app.registerGlobalFilter(MyExceptionFilter)
Solution
Step 1: Recall the NestJS method for global filters
The official method to apply global exception filters is useGlobalFilters() on the app instance.
Step 2: Check the syntax for passing the filter
The filter must be instantiated with new before passing it to useGlobalFilters().
Final Answer:
app.useGlobalFilters(new MyExceptionFilter()) -> Option A
Quick Check:
Global filter method = useGlobalFilters() [OK]
Hint: Use app.useGlobalFilters(new Filter()) in main.ts [OK]
Common Mistakes:
Using incorrect method names like setGlobalFilters
Passing class without instantiation
Confusing with middleware registration methods
3. Given this global exception filter code snippet, what will be the HTTP status code returned when an exception is thrown?
A. Missing @Injectable() decorator on the filter class
B. The @Catch() decorator must specify exception types
C. The catch method must return a value
D. host.getResponse() is incorrect; should use host.switchToHttp().getResponse()
Solution
Step 1: Check how to get response object
In NestJS, to get the HTTP response, use host.switchToHttp().getResponse(), not host.getResponse().
Step 2: Verify other parts
The @Catch() decorator can be empty to catch all exceptions, and the catch method does not need to return a value. @Injectable() is not required for filters.
Final Answer:
host.getResponse() is incorrect; should use host.switchToHttp().getResponse() -> Option D
Quick Check:
Use switchToHttp() to access response [OK]
Hint: Use host.switchToHttp().getResponse() to get response [OK]
Common Mistakes:
Calling host.getResponse() directly
Thinking @Injectable() is mandatory for filters
Expecting catch to return a value
5. You want to create a global exception filter that logs all exceptions and returns a JSON response with a custom message and status code 418 (I'm a teapot) for all errors except HttpExceptions, which should keep their original status. How should you implement the catch method?
hard
A. Always respond with status 418 and ignore HttpException status
B. Check if exception is HttpException, use its status; else log and respond with 418 and custom message
C. Only log exceptions but do not modify the response
D. Throw the exception again to let NestJS handle it
Solution
Step 1: Handle HttpException separately
Check if the exception is an instance of HttpException to preserve its status and message.
Step 2: For other exceptions, log and respond with status 418
Log the error details, then send a JSON response with status 418 and a custom message.
Final Answer:
Check if exception is HttpException, use its status; else log and respond with 418 and custom message -> Option B
Quick Check:
Preserve HttpException status, else respond 418 with log [OK]
Hint: Preserve HttpException status; else respond 418 with log [OK]
Common Mistakes:
Ignoring HttpException status and always sending 418
Not logging exceptions
Re-throwing exceptions instead of handling
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.