Bird
0
0

What is wrong with this interceptor implementation?

medium📝 Debug Q14 of 15
NestJS - Interceptors
What is wrong with this interceptor implementation?
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable {
    try {
      return next.handle();
    } catch (error) {
      console.error('Error caught:', error);
      throw error;
    }
  }
}
AThe interceptor should not throw errors
BThe intercept method must return void, not Observable
CMissing call to next.handle() inside try block
DThe try-catch block won't catch async errors from next.handle()
Step-by-Step Solution
Solution:
  1. Step 1: Understand async error handling in interceptors

    next.handle() returns an Observable, so errors happen asynchronously and are not caught by try-catch.
  2. Step 2: Identify the problem with the try-catch

    The try-catch only catches synchronous errors, so async errors must be handled with RxJS operators like catchError.
  3. Final Answer:

    The try-catch block won't catch async errors from next.handle() -> Option D
  4. Quick Check:

    Async errors need RxJS catchError, not try-catch [OK]
Quick Trick: Use RxJS catchError for async errors, not try-catch [OK]
Common Mistakes:
  • Using try-catch for async Observable errors
  • Assuming intercept returns void
  • Not handling errors inside pipe

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes