All files / src errorHandler.ts

89.39% Statements 59/66
72.5% Branches 29/40
100% Functions 10/10
88.52% Lines 54/61

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163  1x             1x   1x 4x 4x 4x     4x           1x       13x     13x       13x             7x 3x 3x                 10x           10x 4x               1x 18x 18x   18x 4x 4x 4x       14x   1x   1x     3x     5x 5x 1x     4x 4x 3x 3x 3x   1x     4x 2x   2x           1x           1x       1x 1x               2x       2x 2x                 1x 3x         3x     3x 3x         3x     1x  
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  ApolloError,
  AuthenticationError,
  ForbiddenError,
  UserInputError,
} from "apollo-server";
import { GraphQLError } from "graphql";
import { ApplicationError, ErrorPrefix } from "@the-neon/core";
 
const tryParse = (str: string): Error[] | null | undefined => {
  try {
    const result = JSON.parse(str);
    Iif (result.type === "ApplicationError") {
      return result as ApplicationError;
    }
    return result as Error[];
  } catch {
    null;
  }
};
 
const handleApplicationError = (
  errors: ApplicationError[],
  message: string
) => {
  Iif (errors.some((e) => e.prefix === ErrorPrefix.Authentication)) {
    return new AuthenticationError(message);
  }
  Iif (errors.some((e) => e.prefix === ErrorPrefix.Authorization)) {
    return new ForbiddenError(message);
  }
 
  Iif (errors.some((e) => e.prefix === ErrorPrefix.NotSupportedAppVersion)) {
    return new ApolloError(
      "Not supported Application!",
      ErrorPrefix.NotSupportedAppVersion
    );
  }
 
  if (errors.length === 1) {
    const [originalError] = errors;
    return new UserInputError(message, {
      affected: originalError.affected,
      code: originalError.prefix,
      reason: originalError.prefix,
      message: originalError.message || originalError._message,
      severity: "error",
    });
  }
 
  const inputs = errors.map((e) => ({
    affected: e.affected,
    code: e.prefix,
    reason: e.prefix,
    message: e.message || e._message,
  }));
  const code = [...new Set(errors.map((e) => e.prefix))].join("_");
  return new UserInputError(message, {
    code,
    reason: code,
    inputs,
    severity: "error",
  });
};
 
const errorHandler = (ex: GraphQLError): Error => {
  const originalErrorType = ex?.originalError?.["type"] ?? null;
  const originalErrorMessage = ex?.originalError?.["message"] ?? "system error";
 
  if (!originalErrorType && originalErrorMessage) {
    const errors = tryParse(originalErrorMessage);
    if (errors?.length) {
      return handleApplicationError(errors, "");
    }
  }
 
  switch (originalErrorType) {
    case "AuthorizationError":
      return new ForbiddenError(originalErrorMessage);
    case "AuthenticationError":
      return new AuthenticationError(originalErrorMessage);
 
    case "ApplicationError":
      return handleApplicationError([ex.originalError], originalErrorMessage);
 
    case "InputError": {
      const errors = ex.originalError?.["errors"];
      if (!errors) {
        return new UserInputError(originalErrorMessage, { severity: "error" });
      }
 
      const inputs = errors.map((errEntry: Map<string, string> | { key?: string; message?: string }) => {
        if (errEntry instanceof Map) {
          const [field = ""] = [...errEntry.keys()];
          const message = errEntry.get(field) ?? "";
          return { field, message };
        }
        return { field: errEntry.key ?? "", message: errEntry.message ?? "" };
      });
 
      if (inputs.length === 1 && !inputs[0].field) {
        return new UserInputError(inputs[0].message, { severity: "error" });
      }
      return new UserInputError(originalErrorMessage, {
        inputs,
        severity: "error",
      });
    }
    case "NotImplementedYetError":
      return new ApolloError(originalErrorMessage);
    case "ExternalApiError": {
      const configuration: {
        externalSystem: string;
        severity: string;
        debug?: any;
      } = {
        externalSystem: ex.originalError?.["externalApi"],
        severity: "warning",
      };
      logError(ex, configuration);
      return new ApolloError(
        originalErrorMessage,
        "EXTERNAL_API_ERROR",
        configuration
      );
    }
    case "SystemError":
    default: {
      const configuration: Record<string, any> = {
        context: "system error",
        severity: "error",
      };
      logError(ex, configuration);
      return new ApolloError(
        "Something went wrong!",
        "INTERNAL_SERVER_ERROR",
        configuration
      );
    }
  }
};
 
const logError = (ex: any, configuration) => {
  const error = {
    path: "",
    message: "",
    configuration: { ...configuration, debug: ex },
  };
  Iif (ex.path) {
    error.path = ex.path.join(",");
  }
  if (ex.originalError) {
    error.message = ex.originalError.message;
  } else E{
    error.message = ex.message;
  }
 
  console?.error?.(JSON.stringify(error));
};
 
export default errorHandler;