All files error-handler.decorator.ts

100% Statements 17/17
62.5% Branches 5/8
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 381x   1x 3x         3x         3x   3x 3x 3x   2x 1x 1x 1x       1x   1x 1x 1x              
import { Logger } from '@nestjs/common';
 
export const logError = ({ defaultLogger, propagate = true }: { defaultLogger?: Logger, propagate?: boolean } = {}) => {
  return (
    target: unknown,
    propertyKey: string,
    propertyDescriptor: PropertyDescriptor
  ) => {
    const logger = defaultLogger || new Logger(
      `${target.constructor.name}@${propertyKey}`
    );
 
    //get original method
    const originalMethod = propertyDescriptor.value;
    //redefine descriptor value within own function block
    propertyDescriptor.value = function (...args: unknown[]) {
      try {
        const result = originalMethod.apply(this, args);
 
        if(result && result instanceof Promise) {
          return result.catch(err => {
            logger.error(err);
            throw err;
          });
        }
 
        return result;
      } catch (error) {
        logger.error(error.message, error.stack);
        if(propagate){
          throw error;
        }
      }
    };
  };
}