Bird
0
0

Given this interceptor code snippet, what will be logged?

medium📝 component behavior Q13 of 15
NestJS - Interceptors
Given this interceptor code snippet, what will be logged?
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable {
    console.log('Before handler');
    return next.handle().pipe(
      tap(() => console.log('After handler'))
    );
  }
}
AOnly 'Before handler' is logged
BOnly 'After handler' is logged
C'Before handler' then 'After handler' are logged
DNo logs are produced
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the intercept method

    The interceptor logs 'Before handler' immediately, then calls next.handle() which returns an Observable.
  2. Step 2: Understand the tap operator

    The tap operator logs 'After handler' when the Observable emits after the request handler finishes.
  3. Final Answer:

    'Before handler' then 'After handler' are logged -> Option C
  4. Quick Check:

    Logs before and after handler = 'Before handler' then 'After handler' are logged [OK]
Quick Trick: tap() logs after the handler completes [OK]
Common Mistakes:
  • Thinking only one log appears
  • Ignoring the Observable pipe behavior
  • Assuming synchronous logging only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes