Skip to main content

apiErrorHandler

A helper that converts an unknown caught error (Axios error, fetch Response, Error, or plain string) into a human-readable error message string. Use it in API error handling to produce consistent user-facing error text.

Import

import { apiErrorHandler } from "@xocialive/ui-components/utils";

Usage

try {
await api.deleteUser(id);
toast.success("User deleted");
} catch (err) {
toast.error(apiErrorHandler(err));
}

With Axios interceptors

axios.interceptors.response.use(
(response) => response,
(error) => {
const message = apiErrorHandler(error);
toast.error(message);
return Promise.reject(error);
}
);

How it resolves the message

Priority order:

  1. error.response.data.message — Axios HTTP error with a message in the body
  2. error.response.data.title — Axios HTTP error with a title field
  3. error.response.statusText — HTTP status text fallback
  4. error.message — plain Error.message
  5. String(error) — last resort cast to string
  6. "An unexpected error occurred" — ultimate fallback