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.

61 lines (60 loc) • 3.1 kB
import { Logger } from '@nestjs/common'; import { iterate } from 'iterare'; import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context.js'; import { ExceptionsHandler } from '../exceptions/exceptions-handler.js'; import { STATIC_CONTEXT } from '../injector/constants.js'; import { EXCEPTION_FILTERS_METADATA, isEmptyArray, } from '@nestjs/common/internal'; export class RouterExceptionFilters extends BaseExceptionFilterContext { config; applicationRef; static logger = new Logger(RouterExceptionFilters.name); // Applications already warned about their request-scoped or transient // global filters (see "getGlobalMetadata()") static warnedConfigs = new WeakSet(); constructor(container, config, applicationRef) { super(container); this.config = config; this.applicationRef = applicationRef; } create(instance, callback, moduleKey, contextId = STATIC_CONTEXT, inquirerId) { this.moduleContext = moduleKey; const exceptionHandler = new ExceptionsHandler(this.applicationRef); const filters = this.createContext(instance, callback, EXCEPTION_FILTERS_METADATA, contextId, inquirerId); if (isEmptyArray(filters)) { return exceptionHandler; } exceptionHandler.setCustomFilters(filters.reverse()); return exceptionHandler; } getGlobalMetadata(contextId = STATIC_CONTEXT, inquirerId) { const globalFilters = this.config.getGlobalFilters(); if (contextId === STATIC_CONTEXT && !inquirerId) { this.warnAboutScopedGlobalFilters(); return globalFilters; } const scopedFilterWrappers = this.config.getGlobalRequestFilters(); const scopedFilters = iterate(scopedFilterWrappers) .map(wrapper => ({ wrapper, host: wrapper.getInstanceByContextId(this.getContextId(contextId, wrapper), inquirerId), })) // e.g. a request-scoped filter that the request did not instantiate .filter(({ wrapper, host }) => !!host && this.isInstantiated(wrapper, host)) .map(({ host }) => host.instance) .toArray(); return globalFilters.concat(scopedFilters); } /** * Handlers that are not built for a controller (middleware, the "not found" * handler, the exception layer) have no request to resolve request-scoped * or transient global filters for, so these filters are left out. */ warnAboutScopedGlobalFilters() { if (isEmptyArray(this.config.getGlobalRequestFilters()) || RouterExceptionFilters.warnedConfigs.has(this.config)) { return; } RouterExceptionFilters.warnedConfigs.add(this.config); RouterExceptionFilters.logger.warn('Global exception filters (APP_FILTER) with request or transient scope are not applied to exceptions thrown outside of controllers, e.g. in middleware, for unknown routes or while parsing the request body. Register a global filter without a scope as well to handle them.'); } }