# All files / core/exceptions base-exception-filter.ts

94.74% Statements 18/19
72.73% Branches 8/11
100% Functions 3/3
94.74% Lines 18/19

    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
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    581x

    1x
    1x
    1x

    1x
    1x

    1x

    25x

    3x

    3x
    1x

    1x
    1x

    1x

    2x
    2x

    2x

    1x

     import {
      ArgumentsHost,
      ExceptionFilter,
      HttpException,
      HttpServer,
      HttpStatus,
      Inject,
      Logger,
      Optional,
    } from '@nestjs/common';
    import { isObject } from '@nestjs/common/utils/shared.utils';
    import { MESSAGES } from '../constants';
    import { ApplicationReferenceHost } from './../helpers/application-ref-host';

    export class BaseExceptionFilter<T = any> implements ExceptionFilter<T> {
      private static readonly logger = new Logger('ExceptionsHandler');

      @Optional()
      @Inject()
      protected readonly applicationRefHost?: ApplicationReferenceHost;

      constructor(protected readonly applicationRef?: HttpServer) {}

      catch(exception: T, host: ArgumentsHost) {
        const applicationRef =
          this.applicationRef ||
          (this.applicationRefHost && this.applicationRefHost.applicationRef);

        if (!(exception instanceof HttpException)) {
          const body = {
            statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
            message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE,
          };
          applicationRef.reply(host.getArgByIndex(1), body, body.statusCode);
          Iif (this.isExceptionObject(exception)) {
            return BaseExceptionFilter.logger.error(
              exception.message,
              exception.stack,
            );
          }
          return BaseExceptionFilter.logger.error(exception);
        }
        const res = exception.getResponse();
        const message = isObject(res)
          ? res
          : {
              statusCode: exception.getStatus(),
              message: res,
            };

        applicationRef.reply(host.getArgByIndex(1), message, exception.getStatus());
      }

      public isExceptionObject(err): err is Error {
        return isObject(err) && !!(err as Error).message;
      }
    }