All files / utils error.ts

0% Statements 0/29
0% Branches 0/22
0% Functions 0/4
0% Lines 0/27

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                                                                                                                                   
import { ERROR_COPY } from "@/constants/error";
import type { ApiErrorPayload } from "@/types/error";
 
const DEFAULT_ERROR_MESSAGE = ERROR_COPY.unknown;
 
export function getErrorMessage(
  error: unknown,
  fallbackMessage = DEFAULT_ERROR_MESSAGE,
): string {
  switch (true) {
    case error instanceof Error:
      return error.message;
    case typeof error === "string":
      return error;
    case Boolean(error && typeof error === "object" && "message" in error): {
      const message = (error as { message?: string }).message;
      return typeof message === "string" ? message : fallbackMessage;
    }
    default:
      return fallbackMessage;
  }
}
 
function getNestedErrorMessage(
  value: string | { message?: string } | undefined,
): string | undefined {
  if (typeof value === "string") return value;
  return typeof value?.message === "string" ? value.message : undefined;
}
 
export function normalizeErrorMessage(
  rawMessage: string,
  fallbackMessage = DEFAULT_ERROR_MESSAGE,
): string {
  const trimmedMessage = rawMessage.trim();
  if (!trimmedMessage) return fallbackMessage;
 
  try {
    const parsed = JSON.parse(trimmedMessage) as ApiErrorPayload;
 
    const fromError = getNestedErrorMessage(parsed.error);
    const fromMessage = getNestedErrorMessage(parsed.message);
    const fromDetails = getNestedErrorMessage(parsed.details);
 
    switch (true) {
      case typeof fromError === "string":
        return fromError;
      case typeof fromMessage === "string":
        return fromMessage;
      case typeof fromDetails === "string":
        return fromDetails;
      default:
        return trimmedMessage;
    }
  } catch {
    return trimmedMessage;
  }
}
 
export function getDisplayErrorMessage(
  error: unknown,
  fallbackMessage = DEFAULT_ERROR_MESSAGE,
): string {
  return normalizeErrorMessage(getErrorMessage(error, fallbackMessage));
}