> ## Documentation Index
> Fetch the complete documentation index at: https://docs.localpayment.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 错误处理

有效的错误处理对于构建与 Localpayment API 的稳健集成至关重要。了解不同的错误类型及其对应的错误代码将有助于您快速诊断问题并实施相应的解决方案。

我们通过标准化的 HTTP 状态码和详细的错误响应提供全面的错误处理机制。本指南将向您展示如何有效地处理错误，从而构建更具弹性和用户友好的集成方案。

## 概述

妥善处理错误对于创建可靠的支付集成至关重要。Localpayment 在所有 API endpoint 中使用一致的错误处理机制，帮助您快速识别和解决问题。

> [card] [标准化代码](#http-response-codes)
>
> 所有 API endpoint 和支付方式的错误代码一致

> [card] [详细信息](#error-response-structure)
>
> 包含具体错误详情的易于理解的描述

> [card] [最佳实践](#best-practices-for-error-handling)
>
> 处理生产环境中错误的成熟策略

***

## HTTP响应代码

Localpayment 使用标准的 HTTP 状态代码来指示 API 请求的成功或失败：​

| HTTP 代码 | 状态 | 描述 |
| - | - | - |
| 200 | `OK` | 请求成功，响应中包含所请求的数据。 |
| 201 | 创建 | 资源已成功创建（例如，已发起新的付款）。 |
| 400 | 错误的请求 | 请求格式错误，包含无效参数或缺少必填字段。 |
| 401 | 未经授权 | 身份验证失败，凭据无效，或访问令牌缺失/过期。 |
| 403 | 禁止访问 | 我们理解您的请求，但由于权限不足，已被拒绝。 |
| 404 | 未找到 | 找不到请求的资源（例如，无效的 endpoint 或事务 ID）。 |
| 409 | 冲突 | 该请求与资源的当前状态冲突（例如，重复事务）。 |
| 429 | 请求过多 | 超出速率限制。在给定的时间段内发出的请求过多。 |
| 500 | 内部服务器错误 | Localpayment服务器发生意外错误。 |

***

## 错误响应结构

当发生错误时，Localpayment 会返回一个包含详细错误信息的 JSON 对象：

```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
  "status": {
    "code": "300",
    "description": "REJECTED",
    "detail": "Invalid param + [paymentMethod] + [Is mandatory]"
  },
  "errors": [
    {
      "code": "300",
      "description": "REJECTED",
      "detail": "Invalid param + [paymentMethod] + [Is mandatory]"
    }
  ]
}
```

### 错误响应字段

| 字段 | 类型 | 描述 | 例子 |
| - | - | - | - |
| `status.code` | string | Localpayment特定状态代码 | `300` |
| `status.description` | string | 简要错误描述 | `REJECTED` |
| `status.detail` | string | 详细错误信息 | `Invalid param [paymentMethod]` |
| errors\[] | array | 特定错误对象的数组 | 见下文 |
| errors\[].code | string | Localpayment特定错误代码 | `300` |

***

## 内部状态代码参考

虽然 Localpayment 使用标准 HTTP 代码表示请求级别的状态，但 `status.code` 和 `errors[].code` 字段提供了更细粒度的业务逻辑和处理状态。

| 代码范围 | 类别 | 语义含义 | 示例场景 |
| - | - | - | - |
| **1xx** | 待处理 | 交易已启动，但尚待最终确认或执行。 | `100`（待处理），`103`（已批准但未入账） |
| **2xx** | 成功 | 交易已成功处理并完成。 | `200`（已完成） |
| **3xx** | 验证 | 由于缺少参数或参数无效，请求失败。 | `300`（无效参数），`301`（未获该国家授权） |
| **7xx** | 业务逻辑 | 由于银行或业务规则的限制，交易被拒绝。 | `701`（无效账户），`702`（资金不足） |
| **8xx** | 系统/提供商 | 交易被底层服务提供商拒绝或出现内部系统错误。 | `801`（参数错误），`802`（被提供商拒绝） |
| **9xx** | 反转/否定 | 交易已被撤销、退款或提出争议。 | `902`（已退款），`906`（拒付） |

***

## 常见错误场景

### 身份验证错误

```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
  "detail": "Given token not valid for any token type",
  "code": "token_not_valid",
  "messages": [
    {
      "token_class": "AccessToken",
      "token_type": "access",
      "message": "Token is invalid or expired"
    }
  ]
}
```

> [!NOTE]
>
> **解决方案**
>
> 请检查您的 API 凭据并确保您的访问令牌有效。如有需要，请使用令牌刷新 endpoint。

### 验证错误

```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
  "externalId": "46014bdc-c3a7-1b15-8dcf-c7050c1c8199",
  "internalId": "caa4e9aa-f634-497c-ba75-7f88b005ca62",
  "status": {
    "code": "801",
    "description": "REJECTED",
    "detail": "Params error"
  },
  "errors": [
    {
      "code": "300",
      "detail": "Invalid param + [paymentMethod] + doesn't exist for MEX"
    },
    {
      "code": "300",
      "detail": "Invalid param + [payer.bank.account.[number, type | alias]] + must not be null"
    },
    {
      "code": "300",
      "detail": "Invalid param + [payer.document.type] + is invalid for country MEX"
    },
    {
      "code": "300",
      "detail": "Invalid param + [payer.document] + is invalid for payer type"
    },
    {
      "code": "701",
      "detail": "IncorrectAccountNumber"
    }
  ]
}
```

> [!NOTE]
>
> **解决方案**
>
> 请查看 `errors` 数组以了解具体的字段验证问题。请查阅 API 文档了解必填字段和格式规范。

### 业务逻辑错误

```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
  "externalId": "8c0b537a-e907-4d87-93db-5dab9807e093",
  "internalId": "dddfde6c-b61c-4b0e-8916-d88886133c4d",
  "status": {
    "code": "701",
    "description": "REJECTED"
  },
  "errors": [
    {
      "code": "701",
      "detail": "Invalid bank account number. Account number verification failed."
    }
  ]
}
```

> [!NOTE]
>
> **解决方案**
>
> 这些错误需要企业层面解决。请检查账户余额、交易限额，或联系客服了解具体限制。

***

## 错误处理的最佳实践

> [!TIP]
>
> **专业提示**
>
> 从一开始就实施结构化日志记录。包含关联 ID、错误代码和上下文信息，以便在生产环境中出现问题时能够更轻松地进行调试。

### 1.实施全面日志记录

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
function handleApiError(error, context) {
  const logEntry = {
    timestamp: new Date().toISOString(),
    context: context,
    errorCode: error.status?.code,
    errorDescription: error.status?.description,
    errorDetail: error.status?.detail,
    externalId: error.externalId,
    httpStatus: error.httpStatus
  };
  
  console.error('Localpayment API Error:', logEntry);
  // Send to your monitoring system
  sendToMonitoring(logEntry);
}
```

### 用户友好的错误信息

创建从技术错误代码到用户友好消息的映射：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
const errorMessages = {
  '300': 'Please check your information and try again.',
  '701': 'Your payment was declined. Please use a different payment method.',
  '702': 'Payment authorization expired. Please try again.',
  '703': 'Temporary system issue. Please try again in a few minutes.',
  'default': 'An unexpected error occurred. Please contact support.'
};

function getUserMessage(errorCode) {
  return errorMessages[errorCode] || errorMessages['default'];
}
```

### 指数退避重试机制

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
async function makeRequestWithRetry(apiCall, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      // Only retry on certain errors
      if (!isRetryableError(error)) {
        throw error;
      }
      
      if (attempt === maxRetries) {
        throw error;
      }
      
      // Exponential backoff
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

function isRetryableError(error) {
  const retryableCodes = ['500', '502', '503', '504', '800'];
  return retryableCodes.includes(error.status?.code);
}
```

### 断路器模式

安装断路器以防止连锁故障：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
class CircuitBreaker {
  constructor(failureThreshold = 5, resetTimeout = 60000) {
    this.failureThreshold = failureThreshold;
    this.resetTimeout = resetTimeout;
    this.failureCount = 0;
    this.lastFailureTime = null;
    this.state = 'CLOSED';
  }
  
  async call(apiFunction) {
    if (this.state === 'OPEN') {
      if (Date.now() - this.lastFailureTime > this.resetTimeout) {
        this.state = 'HALF_OPEN';
      } else {
        throw new Error('Circuit breaker is OPEN');
      }
    }
    
    try {
      const result = await apiFunction();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }
  
  onSuccess() {
    this.failureCount = 0;
    this.state = 'CLOSED';
  }
  
  onFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();
    
    if (this.failureCount >= this.failureThreshold) {
      this.state = 'OPEN';
    }
  }
}
```

***

## 后续步骤

> [card] [API 参考](https://docs.localpayment.com/zh/reference/api-basics.md)
>
> 完整的错误代码列表及详细说明

> [card] [测试指南](https://docs.localpayment.com/zh/docs/testing.md)
>
> 学习如何在沙箱中测试错误场景

> [card] [支持联系方式](mailto:support@localpayment.com)
>
> 获取针对特定错误场景的帮助


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.