Bird
Raised Fist0
NestJSframework~10 mins

Global exception filters in NestJS - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a global exception filter class in NestJS.

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

@Catch()
export class GlobalExceptionFilter implements [1] {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({ message: 'Internal server error' });
  }
}
Drag options to blanks, or click blank then click option'
AMiddleware
BPipeTransform
CInterceptor
DExceptionFilter
Attempts:
3 left
💡 Hint
Common Mistakes
Using PipeTransform or Interceptor instead of ExceptionFilter
Not implementing any interface
2fill in blank
medium

Complete the code to apply the global exception filter in the main bootstrap function.

NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { GlobalExceptionFilter } from './filters/global-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.[1](new GlobalExceptionFilter());
  await app.listen(3000);
}
bootstrap();
Drag options to blanks, or click blank then click option'
AuseGlobalFilters
BuseGlobalPipes
CuseGlobalInterceptors
DuseMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using useGlobalPipes or useGlobalInterceptors instead
Trying to use useMiddleware which is not a method on the app instance
3fill in blank
hard

Fix the error in the global exception filter to correctly get the HTTP response object.

NestJS
catch(exception: any, host: ArgumentsHost) {
  const ctx = host.[1]();
  const response = ctx.getResponse();
  response.status(500).json({ message: 'Internal server error' });
}
Drag options to blanks, or click blank then click option'
AswitchToHttp
BswitchToRpc
CswitchToWs
DgetHttpContext
Attempts:
3 left
💡 Hint
Common Mistakes
Using switchToRpc or switchToWs which are for other contexts
Using a non-existent method like getHttpContext
4fill in blank
hard

Fill both blanks to create a global exception filter that returns the exception message and status code.

NestJS
catch(exception: any, host: ArgumentsHost) {
  const ctx = host.[1]();
  const response = ctx.getResponse();
  const status = exception.[2] || 500;
  response.status(status).json({
    statusCode: status,
    message: exception.message || 'Internal server error',
  });
}
Drag options to blanks, or click blank then click option'
AswitchToHttp
BgetStatus
Cstatus
DgetResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using getStatus() method which does not exist on exception
Using getResponse() instead of switchToHttp()
5fill in blank
hard

Fill all three blanks to create a global exception filter that logs the error and sends a JSON response with status and message.

NestJS
catch(exception: any, host: ArgumentsHost) {
  const ctx = host.[1]();
  const response = ctx.getResponse();
  const request = ctx.getRequest();
  const status = exception.[2] || 500;
  console.error('Error:', exception.message);
  response.status(status).json({
    statusCode: status,
    timestamp: new Date().toISOString(),
    path: request.[3],
    message: exception.message || 'Internal server error',
  });
}
Drag options to blanks, or click blank then click option'
AswitchToHttp
Bstatus
Curl
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using getResponse() instead of switchToHttp()
Using message instead of status for HTTP status code
Using path instead of url for request path

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

  1. Step 1: Understand the role of exception filters

    Exception filters in NestJS are designed to catch errors and exceptions that occur during request processing.
  2. Step 2: Identify the scope of global exception filters

    Global exception filters apply this error handling across the entire app, centralizing error management.
  3. Final Answer:

    To catch and handle exceptions across the entire application in one place -> Option A
  4. 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

  1. Step 1: Recall the NestJS method for global filters

    The official method to apply global exception filters is useGlobalFilters() on the app instance.
  2. Step 2: Check the syntax for passing the filter

    The filter must be instantiated with new before passing it to useGlobalFilters().
  3. Final Answer:

    app.useGlobalFilters(new MyExceptionFilter()) -> Option A
  4. 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?
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();

    if (exception instanceof HttpException) {
      const status = exception.getStatus();
      response.status(status).json({ message: exception.message });
    } else {
      response.status(500).json({ message: 'Internal server error' });
    }
  }
}
medium
A. 200
B. 500
C. Depends on the exception type
D. 404

Solution

  1. Step 1: Analyze the filter's catch method

    The filter checks if the exception is an instance of HttpException and uses its status code.
  2. Step 2: Determine status code for other exceptions

    If not an HttpException, it returns status 500 with a generic error message.
  3. Final Answer:

    Depends on the exception type -> Option C
  4. Quick Check:

    HttpException status or 500 for others [OK]
Hint: Check if exception is HttpException for status code [OK]
Common Mistakes:
  • Assuming always 500 status
  • Ignoring HttpException status extraction
  • Confusing 404 with 500 errors
4. Identify the error in this global exception filter implementation:
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch()
export class MyFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const response = host.getResponse();
    response.status(400).json({ error: 'Bad Request' });
  }
}
medium
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

  1. Step 1: Check how to get response object

    In NestJS, to get the HTTP response, use host.switchToHttp().getResponse(), not host.getResponse().
  2. 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.
  3. Final Answer:

    host.getResponse() is incorrect; should use host.switchToHttp().getResponse() -> Option D
  4. 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

  1. Step 1: Handle HttpException separately

    Check if the exception is an instance of HttpException to preserve its status and message.
  2. 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.
  3. Final Answer:

    Check if exception is HttpException, use its status; else log and respond with 418 and custom message -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard