0
0
NestJSframework~10 mins

Catch decorator in NestJS - Interactive Code Practice

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

Complete the code to import the Catch decorator from NestJS.

NestJS
import { [1] } from '@nestjs/common';
Drag options to blanks, or click blank then click option'
ACatch
BInjectable
CController
DModule
Attempts:
3 left
💡 Hint
Common Mistakes
Importing the wrong decorator like Controller or Injectable.
Forgetting to import the Catch decorator.
2fill in blank
medium

Complete the code to apply the Catch decorator to an exception filter class.

NestJS
@[1]() 
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    // handle exception
  }
}
Drag options to blanks, or click blank then click option'
AModule
BCatch
CController
DInjectable
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Injectable instead of @Catch.
Not adding parentheses after the decorator.
3fill in blank
hard

Fix the error in the Catch decorator usage to catch only HttpException errors.

NestJS
@Catch([1])
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    // handle HttpException
  }
}
Drag options to blanks, or click blank then click option'
AArgumentsHost
BError
CExceptionFilter
DHttpException
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong class like Error or ArgumentsHost.
Not passing any argument when wanting to catch specific exceptions.
4fill in blank
hard

Fill both blanks to extract the response object and send a JSON error message inside the catch method.

NestJS
catch(exception: HttpException, host: ArgumentsHost) {
  const ctx = host.[1]();
  const response = ctx.[2]();
  response.status(exception.getStatus()).json({
    statusCode: exception.getStatus(),
    message: exception.message
  });
}
Drag options to blanks, or click blank then click option'
AswitchToHttp
BgetResponse
CgetRequest
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Using getRequest instead of getResponse for sending response.
Not switching to HTTP context before getting response.
5fill in blank
hard

Fill the blanks to create a Catch decorator that catches both HttpException and QueryFailedError exceptions.

NestJS
@Catch([1], [2])
export class DatabaseExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(500).json({
      statusCode: 500,
      error: exception.message
    });
  }
}
Drag options to blanks, or click blank then click option'
AHttpException
BQueryFailedError
CExceptionFilter
DArgumentsHost
Attempts:
3 left
💡 Hint
Common Mistakes
Passing non-exception classes.
Not passing multiple exceptions when needed.