import type { DynamicModule } from '@nestjs/common'; import { Module } from '@nestjs/common'; import { APP_FILTER } from '@nestjs/core'; import { FORMATTERS, SENDERS, TRANSFORMERS } from './constants'; import { GlobalExceptionsFilter } from './global-exceptions.filter'; import type { IErrorsFormatter, IErrorsSender, IErrorsTransformer, } from './types'; export interface GlobalExceptionModuleOptions { /** * Formatters are used to transform exceptions to transport specific * final implementations. Usually formatter expects transport agnostic * subclasses of BaseException. */ formatters: IErrorsFormatter[]; /** * Senders are used to actually respond to client (algorithm * is transport specific) */ senders: IErrorsSender[]; /** * Sometimes application throws a lot of unconventional * (not inheriting BaseExceptions). Usually they are throw by * libraries: typeorm, axios, etc. Transformers are used to * catch them and convert to any subtype of BaseException which * will be processed further by transport specific formatters. */ transformers?: IErrorsTransformer[]; } @Module({}) export class GlobalExceptionsModule { static forRoot(options: GlobalExceptionModuleOptions): DynamicModule { return { module: GlobalExceptionsModule, providers: [ { provide: APP_FILTER, useClass: GlobalExceptionsFilter, }, { provide: FORMATTERS, useValue: options.formatters, }, { provide: SENDERS, useValue: options.senders, }, { provide: TRANSFORMERS, useValue: options.transformers || [], }, ], }; } }