Bird
Raised Fist0
NestJSframework~20 mins

Exception filters in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Filter Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a custom exception filter catches an HttpException?

Consider a NestJS controller that throws an HttpException. A custom exception filter catches it and modifies the response. What will the client receive?

NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class CustomFilter 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: 'Filtered: ' + exception.message,
    });
  }
}

// Controller method example:
// throw new HttpException('Original error', 400);
ANo response sent, request hangs
B{"statusCode":400,"message":"Original error"}
C500 Internal Server Error with default message
D{"statusCode":400,"message":"Filtered: Original error"}
Attempts:
2 left
💡 Hint

Think about how the filter modifies the response JSON before sending it.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements an exception filter for all exceptions?

Choose the code snippet that correctly implements a NestJS exception filter catching all exceptions.

A
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch(null)
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: 'Error occurred' });
  }
}
B
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({ message: 'Error occurred' });
  }
}
C
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch(Object)
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: 'Error occurred' });
  }
}
D
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch(Error)
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: 'Error occurred' });
  }
}
Attempts:
2 left
💡 Hint

Recall how to catch all exceptions regardless of type.

🔧 Debug
advanced
2:00remaining
Why does this exception filter not catch exceptions thrown in async methods?

Given this exception filter, exceptions thrown inside async controller methods are not caught. What is the likely cause?

NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class AsyncFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(exception.getStatus()).json({
      message: 'Caught async error',
    });
  }
}

// Controller method example:
// async someMethod() {
//   throw new HttpException('Async error', 400);
// }
AThe filter must implement an async catch method to handle async exceptions.
BThe filter only catches synchronous exceptions; async exceptions must be caught with try/catch.
CThe filter is not bound globally or to the controller, so it doesn't catch async exceptions.
DThe filter's @Catch decorator only catches exceptions thrown outside async methods.
Attempts:
2 left
💡 Hint

Think about how NestJS applies filters and their scope.

❓ state_output
advanced
2:00remaining
What is the response status code when a filter catches a non-HttpException error?

Given a filter that only catches HttpException, what happens if a TypeError is thrown in a controller?

NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpOnlyFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(exception.getStatus()).json({
      message: 'Http error caught',
    });
  }
}

// Controller method example:
// throw new TypeError('Type error');
A500 Internal Server Error with default NestJS error response
B200 OK with empty body
C400 Bad Request with 'Http error caught' message
DNo response sent, request hangs
Attempts:
2 left
💡 Hint

Consider what happens when an exception filter does not catch the thrown error type.

🧠 Conceptual
expert
2:00remaining
How does NestJS determine which exception filter to use when multiple filters apply?

In a NestJS app, multiple exception filters are applied globally, at controller level, and at method level. Which filter will handle an exception?

AThe most specific filter closest to the source of the exception (method > controller > global) handles it.
BThe first registered global filter always handles all exceptions regardless of other filters.
CFilters are merged and all handle the exception in order of registration.
DNestJS randomly picks one filter to handle the exception.
Attempts:
2 left
💡 Hint

Think about filter priority and scope in NestJS.

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