An exception mapping interceptor helps catch errors in your NestJS app and change them into friendly responses.
Exception mapping interceptor in 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(error => { // Map or transform the error here const mappedError = new Error('Custom error message'); return throwError(() => mappedError); }), ); } }
The interceptor uses RxJS catchError to catch errors from the request stream.
You must return an observable error using throwError(() => error) in RxJS 7+.
catchError(error => {
const mappedError = new Error('Something went wrong');
return throwError(() => mappedError);
})catchError(error => {
if (error.status === 404) {
return throwError(() => new Error('Resource not found'));
}
return throwError(() => error);
})catchError(error => {
console.error('Logging error:', error.message);
return throwError(() => new Error('Internal server error'));
})This interceptor catches any error thrown in the controller and changes it to a 400 Bad Request with a custom message.
When you call GET /test, instead of the original error, you get a clean custom error response.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException, HttpStatus } 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(error => { // Map any error to HttpException with status 400 and custom message const customError = new HttpException('Custom bad request error', HttpStatus.BAD_REQUEST); return throwError(() => customError); }), ); } } // Usage example in a controller import { Controller, Get, UseInterceptors } from '@nestjs/common'; @Controller('test') @UseInterceptors(ExceptionMappingInterceptor) export class TestController { @Get() getTest() { throw new Error('Original error'); } }
Interceptors run before and after the request handler, so they can catch errors thrown anywhere in the flow.
Always return a new error inside throwError(() => error) to keep RxJS happy.
You can use this pattern to unify error responses across your app.
An exception mapping interceptor catches errors and changes them to friendly responses.
Use RxJS catchError inside the interceptor to handle errors.
This helps keep your API responses consistent and user-friendly.
Practice
ExceptionMappingInterceptor in NestJS?Solution
Step 1: Understand the role of interceptors
Interceptors in NestJS can modify requests or responses and handle errors.Step 2: Identify the function of exception mapping
An ExceptionMappingInterceptor specifically catches exceptions and converts them into consistent, user-friendly API responses.Final Answer:
To catch exceptions and transform them into user-friendly responses -> Option AQuick Check:
Exception mapping = user-friendly error response [OK]
- Confusing interceptors with middleware for logging
- Thinking interceptors validate data automatically
- Assuming interceptors manage database connections
Solution
Step 1: Recall RxJS operators for error handling
ThecatchErroroperator is designed to catch errors in an observable stream.Step 2: Match operator to interceptor usage
ExceptionMappingInterceptor usescatchErrorto catch exceptions and transform them.Final Answer:
catchError -> Option DQuick Check:
RxJS error handling = catchError [OK]
- 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
intercept(context, next) {
return next.handle().pipe(
catchError(err => {
return throwError(() => new BadRequestException('Mapped error'));
}),
);
}Solution
Step 1: Analyze the catchError block
When an error occurs, catchError catches it and returns a new BadRequestException with a custom message.Step 2: Understand the effect on the client response
The client receives the new BadRequestException with message 'Mapped error' instead of the original error.Final Answer:
A BadRequestException with message 'Mapped error' is sent to the client -> Option CQuick Check:
Error replaced by BadRequestException [OK]
- Thinking original error passes through unchanged
- Assuming no error is sent and request succeeds
- Confusing syntax error with runtime error
intercept(context, next) {
return next.handle().pipe(
catchError(err => {
throw new HttpException('Error occurred', 400);
}),
);
}Solution
Step 1: Understand catchError usage
Inside catchError, you must return an observable error, not throw an error directly.Step 2: Identify correct error handling
The code should returnthrowError(() => new HttpException(...))instead of throwing.Final Answer:
Using throw inside catchError instead of returning an observable error -> Option BQuick Check:
catchError must return observable error, not throw [OK]
- Throwing error directly inside catchError
- Ignoring observable error return requirement
- Assuming status code 400 is wrong here
QueryFailedError exceptions into BadRequestException with a custom message, but lets other exceptions pass unchanged. Which code snippet correctly implements this behavior?Solution
Step 1: Check error type and return observable error
The interceptor must check if the error is aQueryFailedErrorinstance and return a newBadRequestExceptionwrapped inthrowError.Step 2: Pass other errors unchanged as observable errors
Other errors must be re-thrown as observable errors usingthrowErrorto keep the stream consistent.Final Answer:
Option A correctly checks error type and returns observable errors properly -> Option AQuick Check:
Use instanceof + throwError for error mapping [OK]
- Throwing errors directly inside catchError
- Returning error objects instead of observable errors
- Checking error name string instead of instanceof
- Swapping error types incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
