Bird
Raised Fist0
NestJSframework~20 mins

Interceptor interface in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Interceptor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this NestJS interceptor do to the response?
Consider this NestJS interceptor code. What will be the output behavior when applied to a controller method that returns a string?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, map } from 'rxjs';

@Injectable()
export class AppendInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => data + '!!!')
    );
  }
}
AThe interceptor blocks the response and returns an empty string.
BThe interceptor appends three exclamation marks to the original string response.
CThe interceptor converts the response string to uppercase.
DThe interceptor throws an error and stops the response.
Attempts:
2 left
💡 Hint
Look at the map operator inside the pipe and what it does to the data.
❓ lifecycle
intermediate
1:30remaining
When is the intercept() method called in a NestJS interceptor?
In the lifecycle of a NestJS request, at what point does the intercept() method of an interceptor run?
AOnly during application startup.
BOnly after the route handler finishes and sends the response.
CBefore the route handler is executed and after the response is sent.
DBefore the route handler executes and can modify the request or response stream.
Attempts:
2 left
💡 Hint
Interceptors wrap around the route handler execution.
📝 Syntax
advanced
2:30remaining
Which option correctly implements a NestJS interceptor that logs the time taken by a request?
Choose the correct interceptor code that logs the time taken to process a request.
A
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const start = Date.now();
    return next.handle().pipe(
      tap(() =&gt; console.log(`Request took ${Date.now() - start}ms`))
    );
  }
}
B
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, delay, tap } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const start = Date.now();
    return next.handle().pipe(
      delay(1000),
      tap(() =&gt; console.log(`Request took ${Date.now() - start}ms`))
    );
  }
}
C
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, map } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const start = Date.now();
    return next.handle().pipe(
      map(() =&gt; {
        console.log(`Request took ${Date.now() - start}ms`);
        return;
      })
    );
  }
}
D
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const start = Date.now();
    next.handle().subscribe(() =&gt; console.log(`Request took ${Date.now() - start}ms`));
    return next.handle();
  }
}
Attempts:
2 left
💡 Hint
Use tap to perform side effects without changing the data stream.
🔧 Debug
advanced
2:00remaining
Why does this interceptor cause a runtime error?
Identify the cause of the runtime error in this interceptor code.
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, map } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => data.toUpperCase())
    );
  }
}
AThe data might not be a string, so calling toUpperCase() causes a runtime error.
BThe map operator is not imported from rxjs, causing a ReferenceError.
CThe interceptor is missing the @Injectable decorator.
DThe intercept method must return a Promise, not an Observable.
Attempts:
2 left
💡 Hint
Check the type of data before calling string methods.
🧠 Conceptual
expert
1:30remaining
What is the main purpose of the NestJS Interceptor interface?
Choose the best description of what the Interceptor interface allows you to do in NestJS.
ATo define custom decorators for controller methods.
BTo directly access and modify the database before any controller logic runs.
CTo modify incoming requests and outgoing responses by wrapping route handler execution with additional logic.
DTo replace the entire routing system with custom logic for handling HTTP requests.
Attempts:
2 left
💡 Hint
Think about how interceptors wrap around the handler execution.

Practice

(1/5)
1. What is the primary purpose of an interceptor in NestJS?
easy
A. To run code before and after a request is handled
B. To define database schemas
C. To handle HTTP routing
D. To manage user authentication

Solution

  1. Step 1: Understand the role of interceptors

    Interceptors in NestJS are designed to execute code before and after the main request handler runs.
  2. Step 2: Compare with other options

    Database schemas, routing, and authentication are handled by other parts of NestJS, not interceptors.
  3. Final Answer:

    To run code before and after a request is handled -> Option A
  4. Quick Check:

    Interceptor purpose = run code before/after request [OK]
Hint: Interceptors wrap request handling with extra code [OK]
Common Mistakes:
  • Confusing interceptors with middleware
  • Thinking interceptors handle routing
  • Assuming interceptors manage authentication
2. Which method must be implemented when creating a NestJS interceptor?
easy
A. handle()
B. intercept()
C. execute()
D. process()

Solution

  1. Step 1: Recall the interceptor interface

    The NestJS interceptor interface requires implementing the intercept() method.
  2. Step 2: Verify other options

    Methods like handle(), execute(), or process() are not part of the interceptor interface.
  3. Final Answer:

    intercept() -> Option B
  4. Quick Check:

    Interceptor method = intercept() [OK]
Hint: Remember: intercept() runs your interceptor logic [OK]
Common Mistakes:
  • Using handle() instead of intercept()
  • Confusing with middleware method names
  • Forgetting to implement intercept()
3. 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<any> {
    console.log('Before handler');
    return next.handle().pipe(
      tap(() => console.log('After handler'))
    );
  }
}
medium
A. Only 'Before handler' is logged
B. Only 'After handler' is logged
C. 'Before handler' then 'After handler' are logged
D. No logs are produced

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]
Hint: tap() logs after the handler completes [OK]
Common Mistakes:
  • Thinking only one log appears
  • Ignoring the Observable pipe behavior
  • Assuming synchronous logging only
4. 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<any> {
    try {
      return next.handle();
    } catch (error) {
      console.error('Error caught:', error);
      throw error;
    }
  }
}
medium
A. The interceptor should not throw errors
B. The intercept method must return void, not Observable
C. Missing call to next.handle() inside try block
D. The try-catch block won't catch async errors from next.handle()

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]
Hint: 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
5. You want to create an interceptor that measures how long a request takes and adds this duration to the response object as response.duration. Which approach correctly implements this?
hard
A. Record start time, call next.handle(), then use tap() to calculate duration and modify response before returning
B. Record start time, use try-catch around next.handle(), then set duration after catch
C. Modify response before calling next.handle(), then record duration after
D. Use a middleware instead of interceptor to measure time

Solution

  1. Step 1: Understand timing with interceptors

    Start time must be recorded before calling next.handle(), which returns an Observable.
  2. Step 2: Use tap() to run code after handler finishes

    tap() lets you calculate duration after the response is ready and modify it safely.
  3. Step 3: Evaluate options

    Record start time, call next.handle(), then use tap() to calculate duration and modify response before returning correctly uses tap() after next.handle() to set response.duration. Record start time, use try-catch around next.handle(), then set duration after catch uses try-catch incorrectly for async. Modify response before calling next.handle(), then record duration after modifies response too early. Use a middleware instead of interceptor to measure time suggests middleware, which is not the question focus.
  4. Final Answer:

    Record start time, call next.handle(), then use tap() to calculate duration and modify response before returning -> Option A
  5. Quick Check:

    Use tap() after next.handle() to measure time [OK]
Hint: Use tap() after next.handle() to add timing info [OK]
Common Mistakes:
  • Trying to catch async errors with try-catch
  • Modifying response before handler runs
  • Confusing middleware with interceptor roles
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