跳转到主要内容

错误响应格式

KillB 返回标准化的错误响应:
{
  "errorCode": "USER.0001",
  "message": ["User not found"],
  "statusCode": "404",
  "arguments": [
    {
      "key": "userId",
      "value": "invalid-id"
    }
  ]
}

HTTP 状态码

状态含义操作
200成功处理响应
201已创建资源创建成功
400错误请求修复请求参数
401未授权刷新令牌
403禁止检查权限
404未找到资源不存在
409冲突资源已存在
429请求过多实现退避
500服务器错误使用退避重试

常见错误代码

身份验证错误

代码消息解决方案
AUTH.0001无效凭据检查电子邮件/密码
AUTH.0002令牌已过期刷新访问令牌
AUTH.0003无效令牌重新身份验证

用户错误

代码消息解决方案
USER.0001用户未找到验证用户 ID
USER.0002无效文件检查文件格式
USER.0003电子邮件已存在使用不同的电子邮件
USER.0004未成年用户用户必须年满 18 岁

账户错误

代码消息解决方案
ACCOUNT.0001账户未找到验证账户 ID
ACCOUNT.0002无效银行代码检查支持的银行
ACCOUNT.0003无效钱包地址验证地址格式

Ramp 错误

代码消息解决方案
RAMP.0001报价已过期创建新报价
RAMP.0002余额不足检查预充值余额
RAMP.0003用户限额超出升级 KYC 级别
RAMP.0004无效账户验证账户状态

错误处理策略

class KillBAPIError extends Error {
  constructor(response) {
    super(response.message.join(', '));
    this.errorCode = response.errorCode;
    this.statusCode = response.statusCode;
    this.arguments = response.arguments;
  }
}

const makeAPIRequest = async (endpoint, options) => {
  try {
    const response = await fetch(endpoint, options);
    
    if (!response.ok) {
      const error = await response.json();
      throw new KillBAPIError(error);
    }
    
    return await response.json();
    
  } catch (error) {
    if (error instanceof KillBAPIError) {
      // 处理 API 错误
      console.error(`API 错误 ${error.errorCode}:`, error.message);
      
      if (error.statusCode === '401') {
        // 令牌已过期,刷新
        await refreshToken();
        return makeAPIRequest(endpoint, options);
      }
      
      if (error.errorCode === 'RAMP.0001') {
        // 报价已过期,获取新报价
        const newQuote = await getNewQuotation();
        // 使用新报价重试
      }
    }
    
    throw error;
  }
};

重试逻辑

实现指数退避:
const retryWithBackoff = async (fn, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // 不重试客户端错误(4xx)
      if (error.statusCode && error.statusCode < 500) {
        throw error;
      }
      
      // 指数退避
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};

// 使用
const user = await retryWithBackoff(() => createUser(userData));

用户友好消息

将技术错误映射到用户消息:
const getUserMessage = (error) => {
  const messages = {
    'AUTH.0002': '您的会话已过期。请重新登录。',
    'USER.0003': '此电子邮件已注册。',
    'RAMP.0001': '价格报价已过期。请重试。',
    'RAMP.0003': '交易金额超出您的限额。请验证您的身份以提高限额。'
  };
  
  return messages[error.errorCode] || '发生错误。请重试。';
};

下一步