Skip to content

Commit

Permalink
fix(): catch unhandled exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
pooreumu committed Aug 6, 2023
1 parent 8412773 commit f84ed00
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions lib/decorators/on-event.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { extendArrayMetadata } from '@nestjs/common/utils/extend-metadata.util';
import { EVENT_LISTENER_METADATA } from '../constants';
import { OnEventOptions } from '../interfaces';
import { Logger } from '@nestjs/common';

/**
* `@OnEvent` decorator metadata
Expand Down Expand Up @@ -32,10 +33,30 @@ export const OnEvent = (
options?: OnEventOptions,
): MethodDecorator => {
const decoratorFactory = (target: object, key?: any, descriptor?: any) => {
const logger = new Logger('OnEvent');
const originMethod = descriptor.value;
const metaKeys = Reflect.getOwnMetadataKeys(descriptor.value);
const metas = metaKeys.map(key => [
key,
Reflect.getMetadata(key, descriptor.value),
]);
descriptor.value = async function (...args: any[]) {
try {
await originMethod.call(this, ...args);
} catch (error) {
if (error instanceof Error) {
logger.error(error, error.stack);
} else {
logger.error(error);
}
}
};
metas.forEach(([k, v]) => Reflect.defineMetadata(k, v, descriptor.value));

extendArrayMetadata(
EVENT_LISTENER_METADATA,
[{ event, options } as OnEventMetadata],
descriptor.value,
EVENT_LISTENER_METADATA,
[{ event, options } as OnEventMetadata],
descriptor.value,
);
return descriptor;
};
Expand Down

0 comments on commit f84ed00

Please sign in to comment.