This commit is contained in:
2026-08-28 16:54:16 +08:00
parent 22f0528593
commit f28b7f178b
7 changed files with 679 additions and 60 deletions
+23 -1
View File
@@ -18,7 +18,7 @@ interface RetryableRequest extends InternalAxiosRequestConfig {
function unwrap<T>(envelope: ApiEnvelope<T>) {
if (envelope.code !== '200') {
const fieldErrors = asFieldErrors(envelope.data)
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId)
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId)
}
return envelope.data
}
@@ -36,6 +36,7 @@ function mapError(error: unknown) {
error.response?.status,
fieldErrors,
typeof body.traceId === 'string' ? body.traceId : null,
typeof body.requestId === 'string' ? body.requestId : null,
)
}
if (error.code === AxiosError.ERR_NETWORK) return new ApiError('无法连接服务器,请确认后端服务已启动', 'NETWORK_ERROR')
@@ -142,6 +143,7 @@ export async function apiBlobRequest(config: AxiosRequestConfig) {
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
return response.data
} catch (error) {
await throwBlobApiError(error)
throw mapError(error)
}
}
@@ -151,8 +153,28 @@ export async function apiBlobResponseRequest(config: AxiosRequestConfig) {
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
return { blob: response.data, headers: response.headers }
} catch (error) {
await throwBlobApiError(error)
throw mapError(error)
}
}
async function throwBlobApiError(error: unknown) {
if (!axios.isAxiosError(error) || !(error.response?.data instanceof Blob)) return
try {
const body = JSON.parse(await error.response.data.text()) as unknown
if (!isApiEnvelope(body)) return
const fieldErrors = asFieldErrors(body.data)
throw new ApiError(
apiErrorMessage(body.message, fieldErrors),
body.code,
error.response.status,
fieldErrors,
typeof body.traceId === 'string' ? body.traceId : null,
typeof body.requestId === 'string' ? body.requestId : null,
)
} catch (parsedError) {
if (parsedError instanceof ApiError) throw parsedError
}
}
export { ApiError }