# All files / src/helpers errors.ts

70% Statements 14/20
45% Branches 9/20
100% Functions 4/4
70% Lines 14/20

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
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67

    1127x
    1127x
    1127x

    48x

    2x

    2x

    2x

    2x

    48x

    1x
    1x
    1x

    60x
    60x

     import prettyFormat from 'pretty-format';

    export class ErrorWithStack extends Error {
      constructor(message: string | undefined, callsite: Function) {
        super(message);
        Eif (Error.captureStackTrace) {
          Error.captureStackTrace(this, callsite);
        }
      }
    }

    export const prepareErrorMessage = (
      // TS states that error caught in a catch close are of type `unknown`
      // most real cases will be `Error`, but better safe than sorry
      error: unknown,
      name?: string,
      value?: unknown
    ): string => {
      let errorMessage: string;
      if (error instanceof Error) {
        // Strip info about custom predicate
        errorMessage = error.message.replace(
          / matching custom predicate[^]*/gm,
          ''
        );
      } else Eif (error && typeof error === 'object') {
        errorMessage = error.toString();
      } else {
        errorMessage = 'Caught unknown error';
      }

      Iif (name && value) {
        errorMessage += ` with ${name} ${prettyFormat(value, { min: true })}`;
      }
      return errorMessage;
    };

    export const createQueryByError = (
      error: unknown,
      callsite: Function
    ): null => {
      Eif (error instanceof Error) {
        Eif (error.message.includes('No instances found')) {
          return null;
        }
        throw new ErrorWithStack(error.message, callsite);
      }

      throw new ErrorWithStack(
        // generic refining of `unknown` is very hard, you cannot do `'toString' in error` or anything like that
        // Converting as any with extra safe optional chaining will do the job just as well
        `Query: caught unknown error type: ${typeof error}, value: ${(
          error as any
        )?.toString?.()}`,
        callsite
      );
    };

    export function copyStackTrace(target: unknown, stackTraceSource: Error) {
      Eif (target instanceof Error && stackTraceSource.stack) {
        target.stack = stackTraceSource.stack.replace(
          stackTraceSource.message,
          target.message
        );
      }
    }