0
0
NestJSframework~30 mins

Exception mapping interceptor in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Exception Mapping Interceptor in NestJS
📖 Scenario: You are building a NestJS backend API that needs to handle errors gracefully. Instead of sending raw error messages to clients, you want to map exceptions to friendly HTTP responses.
🎯 Goal: Create a NestJS interceptor called ExceptionMappingInterceptor that catches exceptions thrown by route handlers and maps them to custom error responses.
📋 What You'll Learn
Create an interceptor class named ExceptionMappingInterceptor implementing NestInterceptor.
Use RxJS catchError operator to catch exceptions.
Map exceptions to a custom error object with statusCode and message.
Throw an HttpException with the mapped error.
Apply the interceptor to a sample controller method.
💡 Why This Matters
🌍 Real World
Backend APIs often need to handle errors gracefully and send clear messages to clients. This interceptor helps centralize error handling.
💼 Career
Understanding interceptors and error handling in NestJS is essential for backend developers building robust and maintainable APIs.
Progress0 / 4 steps
1
Create the ExceptionMappingInterceptor class
Create a class called ExceptionMappingInterceptor that implements NestInterceptor. Import Injectable from @nestjs/common. Add the @Injectable() decorator above the class.
NestJS
Need a hint?

Remember to import Injectable, NestInterceptor, ExecutionContext, and CallHandler from @nestjs/common.

2
Add RxJS catchError to intercept method
Inside the intercept method, return next.handle() piped with catchError from rxjs/operators. Import catchError from rxjs/operators and throwError from rxjs.
NestJS
Need a hint?

Use next.handle().pipe(catchError(...)) to catch errors from the route handler.

3
Map exceptions to custom error and throw HttpException
Inside the catchError callback, create a variable mappedError with statusCode set to 500 and message set to 'Internal server error'. Import HttpException from @nestjs/common. Throw a new HttpException with mappedError and mappedError.statusCode using throwError(() => new HttpException(...)).
NestJS
Need a hint?

Use throwError(() => new HttpException(...)) to rethrow the mapped error.

4
Apply the ExceptionMappingInterceptor to a controller method
Create a controller class called AppController with a method getHello that throws an error with message 'Something went wrong'. Import Controller, Get, and UseInterceptors from @nestjs/common. Apply the ExceptionMappingInterceptor to the getHello method using @UseInterceptors(ExceptionMappingInterceptor).
NestJS
Need a hint?

Use @UseInterceptors(ExceptionMappingInterceptor) above the method to apply the interceptor.