0
0
NestJSframework~10 mins

Exception mapping interceptor in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Exception mapping interceptor
Request received
Interceptor intercepts
Try to handle request
Exception thrown?
NoReturn response
Yes
Catch exception
Map exception to response
Return mapped response
The interceptor catches exceptions during request handling, maps them to custom responses, and returns them instead of raw errors.
Execution Sample
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ExceptionMappingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      catchError(err => {
        const mappedError = mapException(err);
        return throwError(() => mappedError);
      }),
    );
  }
}

function mapException(err) {
  if (err.status === 404) {
    return new Error('Resource not found');
  }
  return err;
}
This interceptor catches errors from request handlers, maps 404 errors to a custom message, and rethrows them.
Execution Table
StepActionException Thrown?Exception Caught?Exception Mapped?Response Returned
1Request received and passed to interceptorNoNoNoNo
2Handler executes normallyNoNoNoResponse from handler
3Request received and passed to interceptorYes (404 error)NoNoNo
4Interceptor catches exceptionYesYesNoNo
5Interceptor maps exception to custom errorYesYesYesNo
6Interceptor returns mapped error as responseYesYesYesMapped error response
💡 Execution stops after interceptor returns either normal or mapped error response.
Variable Tracker
VariableStartAfter Step 3After Step 5Final
errundefinedError with status 404Mapped Error('Resource not found')Mapped Error('Resource not found')
mappedErrorundefinedundefinedMapped Error('Resource not found')Mapped Error('Resource not found')
Key Moments - 2 Insights
Why does the interceptor catch the exception instead of letting it crash the app?
Because in step 4 the interceptor uses catchError to catch exceptions from the handler, preventing app crash and allowing custom handling.
What happens if the exception is not a 404 error?
At step 5, mapException returns the original error unchanged, so the interceptor rethrows the original error.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is returned at step 2?
AException thrown
BMapped error response
CResponse from handler
DNo response
💡 Hint
Check the 'Response Returned' column at step 2 in the execution_table.
At which step does the interceptor map the exception to a custom error?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look at the 'Exception Mapped?' column in the execution_table.
If the error status was 500 instead of 404, what would happen at step 5?
AException would be unchanged
BException would be mapped to 'Resource not found'
CInterceptor would ignore the error
DResponse would be successful
💡 Hint
Refer to the mapException function logic in the execution_sample.
Concept Snapshot
Exception Mapping Interceptor in NestJS:
- Intercepts requests and catches exceptions from handlers.
- Uses RxJS catchError to handle errors.
- Maps specific exceptions (e.g., 404) to custom errors.
- Returns mapped errors as responses instead of raw exceptions.
- Helps customize error responses and improve app stability.
Full Transcript
In NestJS, an Exception Mapping Interceptor catches errors thrown by request handlers. When a request comes in, the interceptor lets the handler run. If the handler throws an error, the interceptor catches it using RxJS catchError. It then checks the error type and maps it to a custom error if needed, for example changing a 404 error to a 'Resource not found' message. Finally, it returns this mapped error as the response. This prevents raw errors from crashing the app and allows sending friendly error messages to clients.