Bird
Raised Fist0
NestJSframework~20 mins

Catch decorator in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Catch Decorator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when an exception is caught by a Catch decorator?

Consider a NestJS filter using the @Catch() decorator that catches HttpException. What will be the response status code if the filter catches an exception with status 404?

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

@Catch(HttpException)
export class NotFoundFilter 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: 'Resource not found',
    });
  }
}
AThe response status code will be 404 with message 'Resource not found'.
BThe response status code will be 200 with message 'OK'.
CThe response status code will be 500 with message 'Internal server error'.
DThe response status code will be 400 with message 'Bad request'.
Attempts:
2 left
💡 Hint

Think about what exception.getStatus() returns for an HttpException.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies the Catch decorator to catch multiple exception types?

In NestJS, how do you correctly use the @Catch() decorator to catch both HttpException and TypeError exceptions?

A
@Catch(HttpException, TypeError)
export class MultiCatchFilter implements ExceptionFilter { ... }
B
@Catch(HttpException || TypeError)
export class MultiCatchFilter implements ExceptionFilter { ... }
C
@Catch({HttpException, TypeError})
export class MultiCatchFilter implements ExceptionFilter { ... }
D
@Catch([HttpException, TypeError])
export class MultiCatchFilter implements ExceptionFilter { ... }
Attempts:
2 left
💡 Hint

Remember the decorator expects an array for multiple exception types.

🔧 Debug
advanced
2:00remaining
Why does this Catch decorator not catch exceptions as expected?

Given this filter, why does it fail to catch HttpException errors?

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

@Catch()
export class EmptyCatchFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: 'Caught an error' });
  }
}
ABecause the catch method is missing the exception type parameter.
BBecause @Catch() with no arguments does not catch any exceptions.
CBecause the filter does not call next() to continue the pipeline.
DBecause the response object is not properly retrieved from ArgumentsHost.
Attempts:
2 left
💡 Hint

Check what happens when @Catch() has no parameters.

❓ state_output
advanced
2:00remaining
What is the JSON response output of this Catch filter?

What JSON response will be sent when this filter catches a BadRequestException?

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

@Catch(BadRequestException)
export class BadRequestFilter implements ExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();
    response.status(status).json({
      error: 'Bad Request',
      details: exception.message,
    });
  }
}
A{"statusCode":400,"message":"Bad Request Exception"}
B{"error":"Bad Request","details":["Bad Request Exception"]}
C{"error":"Bad Request","details":"Bad Request Exception"}
D{"error":"Bad Request","details":null}
Attempts:
2 left
💡 Hint

Check how exception.message is used in the JSON response.

🧠 Conceptual
expert
2:00remaining
Which statement about the Catch decorator's behavior is true?

Choose the correct statement about how the @Catch() decorator works in NestJS exception filters.

AThe <code>@Catch()</code> decorator can catch exceptions thrown both synchronously and asynchronously in the request lifecycle.
BThe <code>@Catch()</code> decorator can only catch exceptions thrown synchronously inside controllers.
CThe <code>@Catch()</code> decorator automatically logs all caught exceptions to the console.
DThe <code>@Catch()</code> decorator must be used on every controller method to catch exceptions.
Attempts:
2 left
💡 Hint

Think about how NestJS handles exceptions in async code.

Practice

(1/5)
1. What is the primary purpose of the @Catch() decorator in NestJS?
easy
A. To mark a class as an exception filter that handles errors
B. To define a route handler for HTTP requests
C. To inject dependencies into a service
D. To create a middleware function

Solution

  1. Step 1: Understand the role of @Catch()

    The @Catch() decorator is used to mark a class as an exception filter in NestJS, which means it handles errors thrown in the application.
  2. Step 2: Differentiate from other decorators

    Other decorators like route handlers or dependency injections serve different purposes, so @Catch() specifically relates to error handling.
  3. Final Answer:

    To mark a class as an exception filter that handles errors -> Option A
  4. Quick Check:

    Error handling = @Catch() [OK]
Hint: Catch decorator marks error handlers in NestJS classes [OK]
Common Mistakes:
  • Confusing @Catch() with route or middleware decorators
  • Thinking @Catch() injects dependencies
  • Assuming @Catch() handles normal requests
2. Which of the following is the correct syntax to create an exception filter that catches all exceptions using the @Catch() decorator?
easy
A. @Catch()\nexport class AllExceptionsFilter implements ExceptionFilter { ... }
B. @Catch(Error)\nexport class AllExceptionsFilter implements ExceptionFilter { ... }
C. @Catch(HttpException)\nexport class AllExceptionsFilter implements ExceptionFilter { ... }
D. @Catch(Exception)\nexport class AllExceptionsFilter implements ExceptionFilter { ... }

Solution

  1. Step 1: Understand @Catch() usage without parameters

    Using @Catch() with no arguments means the filter will catch all exceptions.
  2. Step 2: Check other options

    Options A, C, and D specify particular exception types, so they do not catch all exceptions.
  3. Final Answer:

    @Catch()\nexport class AllExceptionsFilter implements ExceptionFilter { ... } -> Option A
  4. Quick Check:

    No argument = catch all exceptions [OK]
Hint: Empty @Catch() catches all exceptions [OK]
Common Mistakes:
  • Passing incorrect exception types to @Catch()
  • Using @Catch() with a non-error class
  • Confusing @Catch() with middleware syntax
3. Given the following exception filter code, what will be the output when a NotFoundException is thrown?
import { Catch, ExceptionFilter, ArgumentsHost, NotFoundException } from '@nestjs/common';

@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
  catch(exception: NotFoundException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    response.status(404).json({ message: 'Resource not found' });
  }
}
medium
A. HTTP response with status 404 and default NestJS error message
B. HTTP response with status 500 and default error message
C. No response sent, request hangs
D. HTTP response with status 404 and JSON { message: 'Resource not found' }

Solution

  1. Step 1: Analyze the exception filter behavior

    The filter catches only NotFoundException and sends a 404 status with a custom JSON message.
  2. Step 2: Understand the response sent

    The response is explicitly set to status 404 with JSON { message: 'Resource not found' }, overriding default behavior.
  3. Final Answer:

    HTTP response with status 404 and JSON { message: 'Resource not found' } -> Option D
  4. Quick Check:

    Custom 404 JSON response = HTTP response with status 404 and JSON { message: 'Resource not found' } [OK]
Hint: Filter sends custom response for caught exception type [OK]
Common Mistakes:
  • Assuming default error message is sent
  • Thinking status 500 is returned
  • Missing the JSON response in output
4. Identify the error in the following exception filter code:
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common';

@Catch()
export class MyFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).send('Internal Server Error');
  }
}
medium
A. The response object is not correctly retrieved
B. The exception parameter lacks a type annotation
C. The catch method should return a value
D. The @Catch() decorator must specify an exception type

Solution

  1. Step 1: Check method signature

    The catch method's first parameter exception should have a type annotation, typically unknown or any.
  2. Step 2: Verify other parts

    The @Catch() decorator can be empty to catch all exceptions, returning void is allowed, and response retrieval is correct.
  3. Final Answer:

    The exception parameter lacks a type annotation -> Option B
  4. Quick Check:

    Missing parameter type = The exception parameter lacks a type annotation [OK]
Hint: Always type the exception parameter in catch method [OK]
Common Mistakes:
  • Forgetting to type the exception parameter
  • Thinking @Catch() requires arguments
  • Expecting catch to return a value
5. You want to create a single exception filter that handles both BadRequestException and UnauthorizedException with different custom messages. Which is the correct way to use the @Catch() decorator to achieve this?
hard
A. @Catch()\nexport class MultiExceptionFilter implements ExceptionFilter { ... }
B. @Catch([BadRequestException, UnauthorizedException])\nexport class MultiExceptionFilter implements ExceptionFilter { ... }
C. @Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... }
D. Create two separate filters each with @Catch() for one exception

Solution

  1. Step 1: Understand how to catch multiple exceptions

    The @Catch() decorator accepts multiple exception classes as separate arguments to catch them in one filter.
  2. Step 2: Evaluate options

    @Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } correctly passes multiple exceptions as separate arguments. @Catch([BadRequestException, UnauthorizedException])\nexport class MultiExceptionFilter implements ExceptionFilter { ... } incorrectly passes an array. @Catch()\nexport class MultiExceptionFilter implements ExceptionFilter { ... } catches all exceptions. Create two separate filters each with @Catch() for one exception uses multiple filters, not one.
  3. Final Answer:

    @Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } -> Option C
  4. Quick Check:

    Multiple exceptions as arguments = @Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } [OK]
Hint: Pass multiple exceptions as separate arguments to @Catch() [OK]
Common Mistakes:
  • Passing exceptions as an array to @Catch()
  • Using multiple filters instead of one
  • Using empty @Catch() to catch specific exceptions
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