Performance: Exception mapping interceptor
MEDIUM IMPACT
This affects server response time and client perceived latency by how exceptions are caught and transformed before sending responses.
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class GoodExceptionInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( catchError(err => { // Non-blocking error mapping const mappedError = new Error('Mapped error'); return throwError(() => mappedError); }), ); } }
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class BadExceptionInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( catchError(err => { // Synchronously blocking operation const end = Date.now() + 100; while (Date.now() < end) {} return throwError(() => new Error('Mapped error')); }), ); } }
| Pattern | Event Loop Blocking | Response Delay | Server Load | Verdict |
|---|---|---|---|---|
| Blocking synchronous error mapping | Yes, blocks event loop | High delay per error | Increases under load | [X] Bad |
| Non-blocking asynchronous error mapping | No blocking | Minimal delay | Efficient under load | [OK] Good |