Bird
0
0

Identify the issue in this guard code:

medium📝 Debug Q7 of 15
NestJS - Guards
Identify the issue in this guard code:
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  if (!request.user) {
    throw new UnauthorizedException('User missing');
  }
  return request.user.isVerified;
}
AUsing switchToHttp() instead of getRequest()
BThrowing an exception inside canActivate instead of returning false
CReturning a boolean instead of a Promise<boolean>
DNot checking if isVerified is defined
Step-by-Step Solution
Solution:
  1. Step 1: Understand guard behavior

    Guards should return true or false to allow or deny access.
  2. Step 2: Analyze exception usage

    Throwing exceptions inside canActivate is discouraged; returning false is preferred for denying access.
  3. Final Answer:

    Throwing an exception inside canActivate instead of returning false -> Option B
  4. Quick Check:

    Guards return booleans, not exceptions. [OK]
Quick Trick: Guards should return false, not throw exceptions [OK]
Common Mistakes:
  • Throwing errors instead of returning false
  • Confusing synchronous and asynchronous returns

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes