错误信息示例
演示错误提示的两类场景:表单校验提示(ErrorMessage)与全屏错误页(ErrorShower)。
ErrorShower 全屏错误页
波浪动画的 ERROR 展示,传入 error 文案即可。
404 Not FoundERROR
ErrorMessage 表单校验提示
有错误显示红字;无错误且已提交显示绿勾。
错误信息(Error / ErrorMessage)使用说明
概述
项目的错误提示分四类场景:
| 场景 | 实现 | 说明 |
|---|---|---|
| 表单校验 | ErrorMessage 组件 | 校验失败显示红字、通过显示绿勾 |
| 全屏错误页 | ErrorShower 组件(Error.tsx) | 波浪动画的 ERROR 展示 |
| 接口错误 | Fetcher + Result + toast | code 非 "0" 时 toast 弹出翻译后的 message |
| 错误码文案 | ErrorMessage 消息命名空间 | error key → 多语言文案映射 |
ErrorMessage —— 表单校验提示
受控的校验提示组件,配合 react-hook-form 的 errors / isSubmitted 使用。
import ErrorMessage from "@/common/components/i18n/ErrorMessage";
<ErrorMessage message={errors.userName?.message} submitted={isSubmitted} />
| Prop | 类型 | 必填 | 说明 |
|---|---|---|---|
| message | string | 否 | 错误文案;有值则显示红字 |
| submitted | boolean | 是 | 是否已提交;无错误且已提交时显示绿勾 |
| messageClass | string | 否 | 错误文字样式,默认 text-red-600 |
| rightClass | string | 否 | 绿勾样式,默认 text-red-600 |
渲染逻辑:有 message → 红字;无 message 且 submitted → 绿勾;否则返回空。
ErrorShower —— 波浪 ERROR 动画
Error.tsx 导出的全屏错误展示组件,用 motion-plus 的 splitText 把 "ERROR" 拆成字符做波浪起伏动画。
import ErrorShower from "@/common/components/Error";
<ErrorShower error="404 Not Found" />
| Prop | 类型 | 必填 | 说明 |
|---|---|---|---|
| error | string | 是 | 展示的错误文案 |
依赖:motion + motion-plus(splitText)。样式通过组件内 <style> 注入。
Result —— 接口返回协议
Fetcher 统一按 Result 结构解析响应,code 非 "0" 即视为业务错误。
interface Result {
code: string; // "0" 表示成功
message?: string; // 错误文案(未翻译时使用)
data: any; // 业务数据
key?: string; // 错误码 key(用于多语言翻译)
instruction?: string;
}
Fetcher 内部逻辑(简化):
const result = await response.json() as Result;
if (result.code != "0") {
const message = translator ? translator(result.key) : result.message;
toast.error(message); // react-hot-toast 弹出
}
即:优先用 result.key 查 ErrorMessage 命名空间翻译,查不到再回退到 result.message。
ErrorMessage 消息命名空间
messages/default/{locale}.json 中的 ErrorMessage 命名空间存放错误码 → 文案映射,服务端返回的 key 会作为翻译 key 传入 translator。
| key | 中文 |
|---|---|
| system_server_error | 系统错误,请稍侯再试... |
| global_parameter_null | 参数不能为空... |
| class_not_found | 找不到类... |
新增错误码时,在服务端约定好
key,并在en.json/zh.json的ErrorMessage命名空间里同步补充对应文案。