Bird
Raised Fist0
NestJSframework~10 mins

Exception filters in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Exception filters
Request received
↓
Controller method runs
↓
Exception thrown?
No→Send response
Yes↓
Exception caught by filter
↓
Filter handles exception
↓
Send error response
When a request triggers an error, NestJS passes the error to an exception filter which decides how to respond.
Execution Sample
NestJS
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch(Error)
export class MyFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: exception.message });
  }
}
This filter catches all Error exceptions and sends a 500 JSON response with the error message.
Execution Table
StepActionException StateFilter CalledResponse Sent
1Request received, controller method startsNo exceptionNoNo
2Controller throws Error('Fail')Error('Fail') thrownYesNo
3Filter.catch called with Error('Fail')Error handledYesNo
4Filter sends response status 500 with JSON {message: 'Fail'}HandledYesYes
5Response sent to clientHandledNoYes
💡 Exception handled by filter and response sent, stopping normal flow
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
exceptionnullError('Fail')Error('Fail')HandledHandled
response.statusCodeundefinedundefinedundefined500500
response.bodyundefinedundefinedundefined{"message":"Fail"}{"message":"Fail"}
Key Moments - 2 Insights
Why does the filter catch the exception instead of the controller handling it?
Because the controller threw an exception, NestJS automatically passes it to the registered exception filter as shown in execution_table step 2 and 3.
What happens if the filter does not send a response?
The request would hang because the filter must send a response to end the request, as shown in step 4 where response.status and json are called.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the exception first caught by the filter?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Check the 'Filter Called' column in execution_table rows
According to variable_tracker, what is the response status code after step 3?
Aundefined
B200
C500
D404
💡 Hint
Look at 'response.statusCode' value after Step 3 in variable_tracker
If the controller did not throw an exception, what would happen according to the concept flow?
AFilter would still send a 500 response
BRequest would be handled normally and response sent
CRequest would hang waiting for filter
DFilter would throw an error
💡 Hint
Refer to the 'No exception' branch in concept_flow
Concept Snapshot
Exception filters catch errors thrown in controllers.
Use @Catch decorator to specify exceptions.
Implement catch() to handle and send response.
Filters stop normal flow by sending error responses.
Useful for custom error messages and status codes.
Full Transcript
In NestJS, when a controller method throws an exception, the framework passes it to an exception filter if one is registered. The filter's catch method receives the exception and the context, allowing it to send a custom response. This stops the normal request flow and returns an error response to the client. The example filter catches all Error exceptions and sends a 500 status with a JSON message. The execution table shows the request starting, the exception thrown, the filter catching it, and the response sent. Variables track the exception and response status and body changes. Key moments clarify why filters catch exceptions and the importance of sending a response. The quiz tests understanding of when the filter is called, response status changes, and normal flow without exceptions.

Practice

(1/5)
1. What is the main purpose of an exception filter in NestJS?
easy
A. To catch and handle errors in a centralized way
B. To create database connections automatically
C. To define routes for HTTP requests
D. To manage user authentication

Solution

  1. Step 1: Understand what exception filters do

    Exception filters catch errors thrown during request handling and allow custom responses.
  2. Step 2: Compare with other options

    Options B, C, and D relate to other NestJS features, not error handling.
  3. Final Answer:

    To catch and handle errors in a centralized way -> Option A
  4. Quick Check:

    Exception filters = centralized error handling [OK]
Hint: Exception filters handle errors centrally, not routes or auth [OK]
Common Mistakes:
  • Confusing exception filters with middleware
  • Thinking filters manage routes or database
  • Assuming filters handle authentication
2. Which decorator is used to define an exception filter class in NestJS?
easy
A. @Exception()
B. @Catch()
C. @Filter()
D. @ErrorHandler()

Solution

  1. Step 1: Recall the decorator for exception filters

    The correct decorator to mark a class as an exception filter is @Catch().
  2. Step 2: Verify other decorators

    @Exception(), @Filter(), and @ErrorHandler() are not valid NestJS decorators for filters.
  3. Final Answer:

    @Catch() -> Option B
  4. Quick Check:

    @Catch() marks exception filters [OK]
Hint: Remember: @Catch() catches exceptions in filters [OK]
Common Mistakes:
  • Using @Exception() instead of @Catch()
  • Confusing with @Filter() which is not a decorator
  • Assuming @ErrorHandler() exists in NestJS
3. Given this filter code, what will be the HTTP status code sent when a NotFoundException is thrown?
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' });
  }
}
medium
A. 404
B. 200
C. 500
D. 400

Solution

  1. Step 1: Analyze the response status set in the filter

    The filter explicitly sets the status code to 404 using response.status(404).
  2. Step 2: Understand the exception type caught

    The filter catches NotFoundException, which corresponds to HTTP 404 errors.
  3. Final Answer:

    404 -> Option A
  4. Quick Check:

    NotFoundException triggers 404 status [OK]
Hint: Check response.status() call inside catch method [OK]
Common Mistakes:
  • Assuming default 500 status without custom filter
  • Confusing 404 with 400 or 200
  • Ignoring the status set in the filter
4. Identify the error in this exception filter code:
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 });
  }
}
medium
A. Missing exception type in @Catch() decorator
B. catch method missing return type
C. Using exception.message instead of exception.getMessage()
D. Not importing HttpException class

Solution

  1. Step 1: Check the @Catch() decorator usage

    The @Catch(HttpException) references HttpException, but it is not imported from '@nestjs/common'.
  2. Step 2: Validate other parts

    catch method can omit return type and exception type in loose TS, exception.message is valid.
  3. Final Answer:

    Not importing HttpException class -> Option D
  4. Quick Check:

    Import HttpException for @Catch(HttpException) [OK]
Hint: Import exception classes used in @Catch() [OK]
Common Mistakes:
  • Not importing referenced exception types like HttpException
  • Assuming catch method needs strict return type
  • Thinking exception needs getMessage() method
5. You want to create a global exception filter that catches all exceptions and logs the error before sending a generic message. Which of these is the correct way to apply it globally in NestJS?
hard
A. Register the filter in a module's providers array only
B. Add @Global() decorator to the filter class
C. Use app.useGlobalFilters(new YourFilter()) in main.ts after creating the filter class
D. Call app.setGlobalExceptionFilter(YourFilter) in main.ts

Solution

  1. Step 1: Recall how to apply global filters in NestJS

    Global filters are applied using app.useGlobalFilters() method in the main bootstrap file.
  2. Step 2: Evaluate other options

    @Global() is for modules, not filters; registering in providers is local; app.setGlobalExceptionFilter() does not exist.
  3. Final Answer:

    Use app.useGlobalFilters(new YourFilter()) in main.ts after creating the filter class -> Option C
  4. Quick Check:

    Global filters use app.useGlobalFilters() [OK]
Hint: Global filters need app.useGlobalFilters() call [OK]
Common Mistakes:
  • Using @Global() decorator on filter class
  • Registering filter only in providers without global call
  • Assuming app.setGlobalExceptionFilter() exists
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard