All files / src/utils errorUtils.ts

71.73% Statements 33/46
100% Branches 15/15
66.66% Functions 4/6
71.73% Lines 33/46

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 861x               1x                                             1x               1x 20x 20x 20x 20x 13x 10x 8x   20x         1x 13x 6x 6x   13x 4x 4x   13x 1x 1x   2x 2x         1x 3x 3x 3x         1x 3x 3x 3x 3x  
import { isError } from "./typeGuards";
 
/**
 * Converts any error value to an Error object
 *
 * @param err - The error value to convert
 * @returns An Error object
 */
export function toErrorObject(err: unknown): Error {
  if (isError(err)) {
    return err;
  }
 
  if (err instanceof Object) {
    // If the error is an object with a message property, use that
    if ("message" in err && typeof err.message === "string") {
      return new Error(err.message);
    }
  }
 
  // For strings, numbers, etc.
  return new Error(String(err));
}
 
/**
 * Formats an error for consistent logging
 *
 * @param err - The error to format
 * @param prefix - Optional prefix for the error message
 * @returns A formatted error message
 */
export function formatError(err: unknown, prefix?: string): string {
  const error = toErrorObject(err);
  return prefix ? `${prefix}: ${error.message}` : error.message;
}
 
/**
 * Type guard to check if an error has a message property
 */
export const isErrorWithMessage = (
  error: unknown
): error is { message: string } => {
  return (
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof (error as Record<string, unknown>).message === "string"
  );
};
 
/**
 * Format an error message from various error types
 */
export const formatErrorMessage = (error: unknown): string => {
  if (isErrorWithMessage(error)) {
    return error.message;
  }
 
  if (error === null || error === undefined) {
    return "An unknown error occurred";
  }
 
  if (typeof error === "object" && !("message" in error)) {
    return "An unknown error occurred";
  }
 
  return String(error);
};
 
/**
 * Display an error message in the console
 */
export const displayErrorMessage = (error: unknown): void => {
  const message = formatErrorMessage(error);
  console.error("Error:", message);
};
 
/**
 * Handle an API error with operation context
 */
export const handleApiError = (error: unknown, operation: string): string => {
  const message = formatErrorMessage(error);
  console.error(`API Error (${operation}):`, message);
  return message;
};