FoodEase

Error Helpers

Utilities for extracting and formatting error messages

Overview

Error Helpers provide utility functions for extracting user-friendly error messages from various error response shapes, and for flattening Zod validation errors. This is useful for displaying clear feedback to users regardless of backend or network error structure.

Installation

npx shadcn@latest add https://foodease-dev-registry.cap.reachcinema.io/r/v1/error-helpers.json

Functions

getAPIErrMessage

Extracts a user-friendly error message from an error response object. Handles common error shapes from backend, network, and validation responses.

import { getAPIErrMessage } from "@/lib/errorHelpers"

// API error with messages array
getAPIErrMessage({ error: { data: { messages: ["Invalid credentials"] } } })
// "Invalid credentials"

// Network error with response.data.messages
getAPIErrMessage({ response: { data: { messages: ["Session expired"] } } })
// "Session expired"

// Fallback to default message
getAPIErrMessage({}, "Something went wrong")
// "Something went wrong"

Parameters:

  • resp: The error response object (from API/network/backend)
  • defaultMessage: (optional) Fallback message if no specific error is found

Returns:

  • string: The extracted error message

getDynamicAPIErrMessage

Extracts and joins field-level error messages from a dynamic error object (e.g., { errors: { field: [msg] } }). Falls back to getAPIErrMessage if no field errors are found.

import { getDynamicAPIErrMessage } from "@/lib/errorHelpers"

getDynamicAPIErrMessage({ errors: { email: ["Invalid"], password: ["Too short"] } })
// "email: Invalid, password: Too short"

Parameters:

  • resp: The error response object
  • defaultMessage: (optional) Fallback message

Returns:

  • string: The joined error messages

extractZodErrorMapFlat

Flattens a ZodError into a map of field paths to error messages.

import { extractZodErrorMapFlat } from "@/lib/errorHelpers"

// Example ZodError
const error = {
	issues: [
		{ path: ["user", 0, "name"], message: "Name required" },
		{ path: ["user", 1, "email"], message: "Email invalid" }
	]
};

extractZodErrorMapFlat(error)
// { "user.0.name": "Name required", "user.1.email": "Email invalid" }

Parameters:

  • error: ZodError object

Returns:

  • Record<string, string>: Map of field paths to error messages

On this page