Bird
Raised Fist0
NestJSframework~20 mins

Exception mapping interceptor in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Mapping Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when an exception is thrown inside the interceptor?
Consider a NestJS interceptor that catches exceptions and maps them to a custom error response. What will the client receive if the intercepted method throws a standard Error with message 'Failed operation'?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class ExceptionMappingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError(err => {
        return throwError(() => new Error('Mapped: ' + err.message));
      }),
    );
  }
}

// Controller method throws new Error('Failed operation')
AThe client receives a generic error message 'Internal server error'.
BThe client receives the original error message 'Failed operation' without changes.
CThe client receives an error response with message 'Mapped: Failed operation'.
DThe interceptor swallows the error and the client receives a successful empty response.
Attempts:
2 left
💡 Hint
Think about how catchError modifies the error before rethrowing it.
📝 Syntax
intermediate
2:00remaining
Which option correctly implements an Exception Mapping Interceptor in NestJS?
Select the code snippet that correctly implements an interceptor that catches exceptions and maps them to a custom error message.
A
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class MapExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    try {
      return next.handle();
    } catch (err) {
      throw new Error('Custom error: ' + err.message);
    }
  }
}
B
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class MapExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    return next.handle().pipe(
      catchError(err =&gt; throwError(() =&gt; new Error('Custom error: ' + err.message)))
    );
  }
}
C
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError } from 'rxjs';

@Injectable()
export class MapExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    return next.handle().pipe(
      catchError(err =&gt; {
        return throwError(() =&gt; new Error('Custom error: ' + err.message));
      })
    );
  }
}
D
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';

@Injectable()
export class MapExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    return next.handle().pipe(
      catchError(err =&gt; throwError(() =&gt; new Error('Custom error: ' + err.message)))
    );
  }
}
Attempts:
2 left
💡 Hint
Remember that catchError must return an Observable, and throwError is used to rethrow errors in RxJS.
🔧 Debug
advanced
2:00remaining
Why does this Exception Mapping Interceptor fail to catch errors?
Given the following interceptor code, why does it not catch exceptions thrown by the controller method?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class FaultyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    try {
      return next.handle();
    } catch (err) {
      throw new Error('Intercepted error: ' + err.message);
    }
  }
}
ABecause next.handle() returns an Observable, errors inside it are asynchronous and must be caught using RxJS operators, not try/catch.
BBecause the interceptor is missing the @Catch decorator to catch exceptions.
CBecause the interceptor must return a Promise instead of an Observable to catch errors.
DBecause the try/catch block is placed after the next.handle() call, so it never executes.
Attempts:
2 left
💡 Hint
Think about how Observables handle errors asynchronously.
❓ state_output
advanced
2:00remaining
What is the final error message sent to the client?
An Exception Mapping Interceptor modifies errors by appending ' - intercepted' to the message. The controller throws new Error('Database failure'). What error message does the client receive?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class AppendMessageInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError(err => {
        err.message += ' - intercepted';
        return throwError(() => err);
      }),
    );
  }
}

// Controller throws new Error('Database failure')
AThe client receives an error with message 'Database failure'.
BThe client receives a generic error message 'Internal server error'.
CThe client receives an error with message ' - intercepted'.
DThe client receives an error with message 'Database failure - intercepted'.
Attempts:
2 left
💡 Hint
The interceptor modifies the original error message before rethrowing it.
🧠 Conceptual
expert
2:00remaining
Which statement about Exception Mapping Interceptors in NestJS is TRUE?
Select the correct statement about how Exception Mapping Interceptors work in NestJS.
AThey can transform exceptions thrown by route handlers into custom error responses by catching errors in the Observable stream.
BThey must be implemented as class decorators on controllers to work properly.
CThey replace the need for global exception filters by handling all error mapping internally.
DThey automatically catch all exceptions thrown anywhere in the application without needing to be applied.
Attempts:
2 left
💡 Hint
Think about the scope and purpose of interceptors versus filters.

Practice

(1/5)
1. What is the main purpose of an ExceptionMappingInterceptor in NestJS?
easy
A. To catch exceptions and transform them into user-friendly responses
B. To log all incoming HTTP requests
C. To validate incoming request data automatically
D. To manage database connections

Solution

  1. Step 1: Understand the role of interceptors

    Interceptors in NestJS can modify requests or responses and handle errors.
  2. Step 2: Identify the function of exception mapping

    An ExceptionMappingInterceptor specifically catches exceptions and converts them into consistent, user-friendly API responses.
  3. Final Answer:

    To catch exceptions and transform them into user-friendly responses -> Option A
  4. Quick Check:

    Exception mapping = user-friendly error response [OK]
Hint: Exception interceptors catch errors and format responses [OK]
Common Mistakes:
  • Confusing interceptors with middleware for logging
  • Thinking interceptors validate data automatically
  • Assuming interceptors manage database connections
2. Which RxJS operator is commonly used inside an ExceptionMappingInterceptor to handle errors?
easy
A. map
B. filter
C. tap
D. catchError

Solution

  1. Step 1: Recall RxJS operators for error handling

    The catchError operator is designed to catch errors in an observable stream.
  2. Step 2: Match operator to interceptor usage

    ExceptionMappingInterceptor uses catchError to catch exceptions and transform them.
  3. Final Answer:

    catchError -> Option D
  4. Quick Check:

    RxJS error handling = catchError [OK]
Hint: Use catchError to catch and transform errors in observables [OK]
Common Mistakes:
  • Using map which transforms data but doesn't catch errors
  • Confusing filter with error handling
  • Using tap which is for side effects, not error catching
3. Given this ExceptionMappingInterceptor code snippet, what will be the output if the handler throws an error?
intercept(context, next) {
  return next.handle().pipe(
    catchError(err => {
      return throwError(() => new BadRequestException('Mapped error'));
    }),
  );
}
medium
A. The original error is sent to the client
B. No error is sent; the request succeeds silently
C. A BadRequestException with message 'Mapped error' is sent to the client
D. A syntax error occurs and the app crashes

Solution

  1. Step 1: Analyze the catchError block

    When an error occurs, catchError catches it and returns a new BadRequestException with a custom message.
  2. Step 2: Understand the effect on the client response

    The client receives the new BadRequestException with message 'Mapped error' instead of the original error.
  3. Final Answer:

    A BadRequestException with message 'Mapped error' is sent to the client -> Option C
  4. Quick Check:

    Error replaced by BadRequestException [OK]
Hint: catchError replaces original error with mapped exception [OK]
Common Mistakes:
  • Thinking original error passes through unchanged
  • Assuming no error is sent and request succeeds
  • Confusing syntax error with runtime error
4. Identify the error in this ExceptionMappingInterceptor code:
intercept(context, next) {
  return next.handle().pipe(
    catchError(err => {
      throw new HttpException('Error occurred', 400);
    }),
  );
}
medium
A. No error; code is correct
B. Using throw inside catchError instead of returning an observable error
C. Incorrect status code 400 instead of 500
D. Missing import for HttpException

Solution

  1. Step 1: Understand catchError usage

    Inside catchError, you must return an observable error, not throw an error directly.
  2. Step 2: Identify correct error handling

    The code should return throwError(() => new HttpException(...)) instead of throwing.
  3. Final Answer:

    Using throw inside catchError instead of returning an observable error -> Option B
  4. Quick Check:

    catchError must return observable error, not throw [OK]
Hint: Return throwError inside catchError, don't throw directly [OK]
Common Mistakes:
  • Throwing error directly inside catchError
  • Ignoring observable error return requirement
  • Assuming status code 400 is wrong here
5. You want to create an ExceptionMappingInterceptor that converts all QueryFailedError exceptions into BadRequestException with a custom message, but lets other exceptions pass unchanged. Which code snippet correctly implements this behavior?
hard
A. return next.handle().pipe(catchError(err => { if (err instanceof QueryFailedError) { return throwError(() => new BadRequestException('Invalid query')); } return throwError(() => err); }));
B. return next.handle().pipe(catchError(err => { if (err instanceof QueryFailedError) { throw new BadRequestException('Invalid query'); } throw err; }));
C. return next.handle().pipe(catchError(err => { if (err.name === 'QueryFailedError') { return new BadRequestException('Invalid query'); } return err; }));
D. return next.handle().pipe(catchError(err => { if (err instanceof BadRequestException) { return throwError(() => new QueryFailedError()); } return throwError(() => err); }));

Solution

  1. Step 1: Check error type and return observable error

    The interceptor must check if the error is a QueryFailedError instance and return a new BadRequestException wrapped in throwError.
  2. Step 2: Pass other errors unchanged as observable errors

    Other errors must be re-thrown as observable errors using throwError to keep the stream consistent.
  3. Final Answer:

    Option A correctly checks error type and returns observable errors properly -> Option A
  4. Quick Check:

    Use instanceof + throwError for error mapping [OK]
Hint: Use instanceof and return throwError for mapped and original errors [OK]
Common Mistakes:
  • Throwing errors directly inside catchError
  • Returning error objects instead of observable errors
  • Checking error name string instead of instanceof
  • Swapping error types incorrectly
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