errors.ts
1.77 KB
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
import type { RequestConfig } from './facade';
/**
* 带上下文的请求异常。
*
* 独立成模块是为了让 strategies.ts 能抛它而不必运行时反向 import facade
* (facade 会 import strategies,循环依赖在 CJS 产物里会拿到 undefined)。
* facade 原样 re-export,对 `@uj/api-core` 的公开 API 没有变化。
*/
export class RequestError extends Error {
readonly isRequestError = true;
code?: string | number;
/** 业务失败信封里的 data 字段(web 老壳 `Object.assign(new Error(msg), { code, data })` 的语义)。 */
data?: unknown;
config?: RequestConfig;
response?: unknown;
cause?: unknown;
constructor(message: string, init: Partial<RequestError> = {}) {
super(message);
this.name = 'RequestError';
if (init.code !== undefined) this.code = init.code;
if (init.data !== undefined) this.data = init.data;
if (init.config !== undefined) this.config = init.config;
if (init.response !== undefined) this.response = init.response;
if (init.cause !== undefined) this.cause = init.cause;
}
}
/**
* 「是不是 RequestError」只能靠标记字段,不能靠 instanceof。
*
* wujie 子应用跑在自己的 iframe realm 里:主壳 props.request 抛出的错误在子应用侧
* `instanceof Error === false`。用 instanceof 判定会把一条带了人话文案与业务码的失败
* 降级成 `String(err)`,顺带丢掉 code —— 于是业务错误被当成传输错误(多 toast、多重试),
* 页面提示退化成「操作失败,请稍后重试」。`isRequestError` 是实例自有字段,跨 realm 仍在。
*/
export function isRequestError(error: unknown): error is RequestError {
return Boolean(error) && (error as { isRequestError?: unknown }).isRequestError === true;
}