feat!(): add custom execution context

This commit is contained in:
Morb0
2021-01-03 01:30:57 +03:00
parent 85bb916709
commit af632ea471
64 changed files with 899 additions and 69 deletions

View File

@@ -0,0 +1,34 @@
import { ArgumentsHost, Logger } from '@nestjs/common';
import { MESSAGES } from '@nestjs/core/constants';
import { Context } from 'telegraf';
import { TelegrafExceptionFilter } from '../interfaces/telegraf-exception-filter.interface';
import { TelegrafException } from '../errors';
import { isErrorObject } from '../helpers/is-error-object.helper';
import { TelegrafArgumentsHost } from '../execution-context';
export class BaseTelegrafExceptionFilter<TError = any>
implements TelegrafExceptionFilter {
private static readonly logger = new Logger('TelegrafExceptionsHandler');
catch(exception: TError, host: ArgumentsHost): void {
const context = TelegrafArgumentsHost.create(host).getContext<Context>();
this.handleError(exception, context);
}
public handleError(exception: TError, context: Context): void {
if (!(exception instanceof TelegrafException)) {
return this.handleUnknownError(exception, context);
}
context.reply(exception.message);
}
public handleUnknownError(exception: TError, context: Context): void {
context.reply(MESSAGES.UNKNOWN_EXCEPTION_MESSAGE);
const errorMessage = isErrorObject(exception)
? exception.message
: exception;
BaseTelegrafExceptionFilter.logger.error(errorMessage);
}
}

1
lib/exceptions/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './base-telegraf-exception-filter';

View File

@@ -0,0 +1,48 @@
import { ArgumentsHost } from '@nestjs/common';
import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions';
import { BaseTelegrafExceptionFilter } from './base-telegraf-exception-filter';
import { TelegrafException } from '../errors';
import { InvalidExceptionFilterException } from '@nestjs/core/errors/exceptions/invalid-exception-filter.exception';
import { isEmpty } from '@nestjs/common/utils/shared.utils';
export class TelegrafExceptionsHandler extends BaseTelegrafExceptionFilter {
private filters: ExceptionFilterMetadata[] = [];
public handle(
exception: Error | TelegrafException | any,
host: ArgumentsHost,
): void {
const isFilterInvoked = this.invokeCustomFilters(exception, host);
if (!isFilterInvoked) {
super.catch(exception, host);
}
}
public invokeCustomFilters<T = any>(
exception: T,
args: ArgumentsHost,
): boolean {
if (isEmpty(this.filters)) return false;
const filter = this.filters.find(({ exceptionMetatypes }) => {
const hasMetatype =
!exceptionMetatypes.length ||
exceptionMetatypes.some(
(ExceptionMetatype) => exception instanceof ExceptionMetatype,
);
return hasMetatype;
});
filter && filter.func(exception, args);
return !!filter;
}
public setCustomFilters(filters: ExceptionFilterMetadata[]): void {
if (!Array.isArray(filters)) {
throw new InvalidExceptionFilterException();
}
this.filters = filters;
}
}