41 lines
1.9 KiB
TypeScript
41 lines
1.9 KiB
TypeScript
type FieldIssue = { field: string; message: string };
|
||
|
||
function describeIssues(message: string, issues: FieldIssue[]) {
|
||
const details = issues.slice(0, 3).map((issue) => `${issue.field}:${issue.message}`);
|
||
return details.length ? `${message}(${details.join(';')})` : message;
|
||
}
|
||
|
||
/** 只展示服务端错误信封的业务说明,避免把请求或授权信息带入错误提示。 */
|
||
export function requestError(body: unknown, status: number) {
|
||
const error = body && typeof body === 'object' && 'error' in body
|
||
? body.error
|
||
: null;
|
||
const info = error && typeof error === 'object'
|
||
? error as { message?: unknown; details?: unknown }
|
||
: null;
|
||
const message = typeof info?.message === 'string'
|
||
? info.message
|
||
: `请求失败(HTTP ${status})`;
|
||
const issues = Array.isArray(info?.details)
|
||
? info.details.filter((item): item is FieldIssue =>
|
||
!!item && typeof item === 'object' &&
|
||
typeof item.field === 'string' && typeof item.message === 'string')
|
||
: [];
|
||
return Object.assign(new Error(describeIssues(message, issues)), { status });
|
||
}
|
||
|
||
/** Chrome 消息只返回可序列化错误,交给内容脚本显示,避免后台未处理异常。 */
|
||
export function backgroundError(error: unknown) {
|
||
return { error: { message: error instanceof Error ? error.message : '操作失败,请重试' } };
|
||
}
|
||
|
||
export function unwrapBackgroundResponse<T>(response: unknown): T {
|
||
if (!response || typeof response !== 'object')
|
||
throw new Error('插件后台未响应,请重载扩展并刷新商品页');
|
||
if ('error' in response && response.error && typeof response.error === 'object') {
|
||
const error = response.error as { message?: unknown };
|
||
throw new Error(typeof error.message === 'string' ? error.message : '操作失败,请重试');
|
||
}
|
||
return response as T;
|
||
}
|