---

title: API网关错误码统一与客户端SDK落地最佳实践

keywords:

  • 错误码
  • 网关
  • SDK
  • Trace-ID
  • 重试建议
  • i18n
  • 统一Schema
  • 映射
  • 指标
  • 采样

description: 在API网关统一错误码与响应Schema,并生成客户端SDK解析器与重试建议,涵盖Trace-ID传播、国际化与指标采样,附网关封装与SDK示例。

categories:

  • 文章资讯
  • 技术教程

---

一、网关错误Schema

type ErrorPayload = { code: string; message: string; traceId: string; hint?: string }
const statusByCode: Record<string, number> = { bad_request: 400, unauthorized: 401, forbidden: 403, not_found: 404, rate_limited: 429, server_error: 500 }

二、网关封装

type Req = { headers: Record<string, string | undefined> }
type Res = { setHeader: (k: string, v: string) => void; status: (n: number) => Res; end: (b?: string) => void }

function traceId(req: Req): string { return req.headers['x-trace-id'] || Math.random().toString(36).slice(2) }
function setHeaders(res: Res, id: string) { res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Trace-Id', id) }
function sendError(req: Req, res: Res, code: keyof typeof statusByCode, msg: string, hint?: string) { const id = traceId(req); setHeaders(res, id); const p: ErrorPayload = { code, message: msg, traceId: id, hint }; res.status(statusByCode[code]).end(JSON.stringify(p)) }

三、SDK解析与建议

type SdkError = { code: string; message: string; traceId: string; retry?: boolean }
function parseError(resp: Response): Promise<SdkError> { return resp.json().then((p: any) => ({ code: String(p.code || 'server_error'), message: String(p.message || 'error'), traceId: String(p.traceId || ''), retry: resp.status === 429 || resp.status >= 500 })) }

四、国际化与提示

const i18n: Record<string, string> = { unauthorized: '未授权', forbidden: '禁止访问', not_found: '资源不存在', rate_limited: '请求过于频繁', server_error: '服务异常' }
function i18nMsg(code: string): string { return i18n[code] || '请求错误' }

五、指标采样

class Metrics { counts = new Map<string, number>(); inc(k: string) { const n = (this.counts.get(k) || 0) + 1; this.counts.set(k, n) } }
function sample(p: number): boolean { return Math.random() < p }
function record(metrics: Metrics, code: string, p = 0.1) { if (sample(p)) metrics.inc(code) }

六、验收清单

  • 网关统一code→HTTP映射与错误Schema;传播X-Trace-Idnosniff头。
  • SDK解析错误并提供重试建议;国际化提示与统一消息。
  • 指标采样记录错误码分布;CI检测错误Schema一致性与覆盖率。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部