UNPKG

@nestjs/core

Version:

The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.

64 lines (63 loc) • 2.6 kB
import { isObservable } from 'rxjs'; import { types } from 'util'; import { InvalidExceptionFilterException } from '../errors/exceptions/invalid-exception-filter.exception.js'; import { BaseExceptionFilter } from './base-exception-filter.js'; import { selectExceptionFilterMetadata, isEmptyArray, } from '@nestjs/common/internal'; export class ExceptionsHandler extends BaseExceptionFilter { filters = []; next(exception, ctx) { if (this.invokeCustomFilters(exception, ctx)) { return; } super.catch(exception, ctx); } setCustomFilters(filters) { if (!Array.isArray(filters)) { throw new InvalidExceptionFilterException(); } this.filters = filters; } invokeCustomFilters(exception, ctx) { if (isEmptyArray(this.filters)) { return false; } const filter = selectExceptionFilterMetadata(this.filters, exception); if (!filter) { return false; } const result = filter.func(exception, ctx); if (types.isPromise(result)) { // What an async filter returns is known once it settles. Only that is // handled here: a filter that rejects is left as it is. void result.then(value => { if (this.isLeftUnanswered(value, ctx)) { this.answerLeftException(exception, ctx); } }); return true; } return !this.isLeftUnanswered(result, ctx); } /** * A filter written for another context returns what that context is to * send, and leaves an HTTP request unanswered when it is bound to HTTP * routes as well (as a global filter is): an RPC exception filter (e.g. a * GrpcExceptionFilter in a hybrid application) returns a stream, or a * promise of one, and a GraphQL exception filter the error to report. A * filter that answers the request returns nothing, or e.g. the response. */ isLeftUnanswered(result, ctx) { return ((isObservable(result) || result instanceof Error) && !this.applicationRef?.isHeadersSent(ctx.getArgByIndex(1))); } answerLeftException(exception, ctx) { try { super.catch(exception, ctx); } catch (err) { // Nothing catches what the built-in filter throws (e.g. for a body that // cannot be serialized) once an async filter has settled this.handleUnknownError(err, ctx, (this.applicationRef ?? this.httpAdapterHost?.httpAdapter)); } } }