Discover how one interceptor can save you from endless error-handling headaches!
Why Exception mapping interceptor in NestJS? - Purpose & Use Cases
Imagine building a NestJS app where every time an error happens, you manually catch it in each controller method and transform it into a user-friendly message.
You have to repeat this error handling code everywhere, making your controllers bulky and hard to read.
Manually catching and transforming errors in every method is tiring and easy to forget.
This leads to inconsistent error responses and scattered error logic, making maintenance a nightmare.
An exception mapping interceptor centralizes error handling.
It catches exceptions globally, maps them to consistent responses, and keeps your controller code clean and focused.
try { /* controller logic */ } catch (e) { return { message: 'Error occurred' }; }
@UseInterceptors(ExceptionMappingInterceptor) // controller logic without try-catchIt enables clean, consistent, and maintainable error handling across your entire NestJS application.
In an online store app, when a product is not found, the interceptor maps the error to a clear 404 response instead of repeating this logic in every product-related controller.
Manual error handling clutters code and causes inconsistency.
Exception mapping interceptor centralizes and standardizes error responses.
This keeps your code clean and easier to maintain.
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
