Skip to Content

apiErrorText

Gets the message to show for a failed API call: the server’s Vietnamese message when there is one, a connection message when the server can’t be reached, or a fallback.

Usage

app/pos/page.tsx
import { Alert } from "antd"; import { useApiClient } from "app/api"; import { apiErrorText, useRequest } from "app/hooks"; export default function PosPage() { const api = useApiClient(); const { data, error } = useRequest(() => api.products.list({ pageSize: 100 })); if (error) return <Alert type="error" message={apiErrorText(error, "Không tải được danh sách hàng")} />; // … }

Signature

app/hooks.ts
function apiErrorText(e: any, fallback?: string): string;

Parameters

  • e: an error caught from useApiClient() or useApi().
  • fallback: the text used when the server sent none, “Có lỗi xảy ra, vui lòng thử lại” by default.

Returns

A string, first match wins:

  1. No response (offline, server not answering): “Không kết nối được máy chủ — kiểm tra mạng rồi thử lại”.
  2. message (or error) in the server’s { error, message, code } error body.
  3. fallback, instead of English text such as “Request failed with status code 500”.

Examples

Most pages never call it. In apps framed by AppShell from manh/shell, every failed API call shows its message by itself; useAction, submit and tableRequest use this function too. Call apiErrorText when you show the error somewhere of your own, such as an Alert in the page.

To keep one call from showing its error, pass { silent: true } in that call’s axios config.

Next steps

  • Error codes: the error body and the codes the server sends.
  • useApi: retries on failed reads and sign-out when the session expires.
Last updated