> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.redpincompany.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.redpincompany.com/_mcp/server.

# Error handling

> Comprehensive guide to handling errors and implementing robust error recovery

This guide covers error response formats, common error scenarios, and best practices for implementing robust error handling in your Redpin API integration.

## Error response format

All API errors follow a consistent response structure based on the actual OpenAPI specification:

```json
{
  "code": "INVALID_PARAMETER",
  "description": "payment_id is required",
  "type": "Validation Error",
  "field": "payment_id"
}
```

**Response fields:**

* `code` - Specific error code for programmatic handling
* `description` - Human-readable error description
* `type` - Error category (Validation Error, Authentication Error, Server Error)
* `field` - Field name causing the error (for validation errors, optional)
* `details` - Additional error context (optional)

## Common error scenarios

#### Authentication errors (401)

> **Warning**
>
> Authentication failures require immediate attention as they prevent all API access.

**Common causes:**

* Missing or invalid bearer token
* Expired access token
* Incorrect client credentials

**Example response:**

```json
{
  "code": "UNAUTHORIZED",
  "description": "Missing or invalid bearer token",
  "type": "Authentication Error"
}
```

**Handling strategy:**

* Clear invalid token from storage
* Refresh access token using client credentials flow
* Retry original request with new token

#### Validation errors (400)

**Common causes:**

* Missing required fields
* Invalid data formats
* Unsupported values
* Field-specific validation failures

**Example response:**

```json
{
  "code": "INVALID_PARAMETER",
  "description": "email is required",
  "type": "Validation Error",
  "field": "email"
}
```

**Handling strategy:**

* Check if `field` is present for field-specific errors
* Highlight the problematic field in your UI
* Display user-friendly error message
* Prevent form submission until resolved

#### Resource not found (404)

**Common causes:**

* Invalid customer ID
* Non-existent resource references
* Expired or deleted entities

**Example response:**

```json
{
  "code": "RESOURCE_NOT_FOUND",
  "description": "Customer not found",
  "type": "Resource Error"
}
```

**Handling strategy:**

* Display clear "not found" message to user
* Offer alternative actions (create new resource, search, etc.)
* Log the error for debugging purposes
* Redirect to appropriate fallback page

#### Server errors (500)

**Common causes:**

* Temporary service disruption
* Database connectivity issues
* System overload

**Example response:**

```json
{
  "code": "INTERNAL_ERROR",
  "description": "Unexpected server-side failure", 
  "type": "Server Error"
}
```

**Handling strategy:**

* Log error details for monitoring and debugging
* Implement exponential backoff for retries
* Limit retry attempts (typically 3-5 attempts)
* Display user-friendly "service unavailable" message
* Provide estimated recovery time if known

## Retry strategies

> **Info**
>
> Implement intelligent retry logic to handle transient failures gracefully while avoiding excessive API calls.

#### Exponential backoff implementation

**Key principles:**

* Start with 1-second base delay
* Double delay after each retry (exponential growth)
* Add random jitter to prevent thundering herd
* Cap maximum delay at 30 seconds
* Use for temporary failures only

### Retry conditions

#### Retry these errors

* Server errors (500, 502, 503, 504)
* Network timeouts
* Rate limiting (429)
* Connection failures

#### Don't retry these errors

* Authentication failures (401)
* Validation errors (400)
* Resource not found (404)
* Business logic errors

#### Retry implementation guidelines

**Implementation steps:**

1. Set maximum retry limit (typically 3-5 attempts)
2. Check if error is retryable before attempting
3. Apply exponential backoff between attempts
4. Log each retry attempt for monitoring
5. Fail fast on non-retryable errors

**Retryable error conditions:**

* Server errors (500+)
* Rate limiting (429)
* Network timeouts
* Connection failures

## Business logic errors

#### Quote expiration

**Scenario:** Quote expires before creating payment

```json
{
  "code": "QUOTE_EXPIRED",
  "description": "Quote has expired and can no longer be used",
  "type": "Business Error"
}
```

**Recovery:**

* Generate new quote automatically using original parameters
* Update quote display with new rate and expiry
* Notify user of rate change and request confirmation

#### Insufficient balance

**Scenario:** Customer has insufficient funds for payment

```json
{
  "code": "INSUFFICIENT_BALANCE",
  "description": "Customer balance insufficient for payment amount",
  "type": "Business Error"
}
```

**Recovery:**

* Display funding instructions with required amount
* Show supported funding methods (bank transfer, etc.)
* Provide clear timeline for fund availability
* Offer to pause payment until funds are available

#### Customer verification required

**Scenario:** Additional KYC verification needed

```json
{
  "code": "VERIFICATION_REQUIRED", 
  "description": "Customer requires additional verification",
  "type": "Business Error"
}
```

**Recovery:**

* Redirect user to KYC verification process
* Explain required documents and timeline
* Save payment progress for completion after verification
* Provide status updates on verification progress

## Error monitoring

#### Structured logging best practices

**Essential logging elements:**

* Error code and type for categorization
* Request context (customer ID, endpoint, request ID)
* User agent and timestamp information
* Stack trace for debugging purposes
* Correlation IDs for request tracing

**Logging levels:**

* ERROR: All API errors and exceptions
* WARN: Retry attempts and recoverable issues
* INFO: Successful error recoveries
* DEBUG: Detailed troubleshooting information

#### Error rate metrics

* Authentication errors (401)
* Validation errors (400)
* Server errors (500+)
* Business logic errors
* Overall error rate trends

#### Performance metrics

* Average response times
* Retry attempt frequency
* Recovery success rates
* Time to resolution
* Peak error periods

## User experience

#### User-friendly error messaging

> **Tip**
>
> Provide clear, actionable error messages that help users understand what went wrong and how to fix it.

**Message examples by error type:**

* `INVALID_PARAMETER`: "Please check the highlighted field and try again"
* `QUOTE_EXPIRED`: "Exchange rate expired. We've generated a new rate for you"
* `INSUFFICIENT_BALANCE`: "Please add funds to your account to continue"
* `VERIFICATION_REQUIRED`: "Additional verification needed to process this payment"

**Message guidelines:**

* Use simple, non-technical language
* Provide clear next steps
* Include relevant context
* Avoid exposing internal system details

#### Progressive error disclosure

**User experience layers:**

* **Primary**: User-friendly message prominently displayed
* **Secondary**: Recovery actions and next steps
* **Tertiary**: Technical details (debug mode only)
* **Background**: Full error logging for troubleshooting

**Context-aware help:**

* Link to relevant documentation
* Suggest alternative approaches
* Provide contact information for complex issues
* Include estimated resolution times

## Testing error scenarios

#### Comprehensive error testing

> **Check**
>
> Use sandbox environment to test all error scenarios before production deployment.

**Critical test scenarios:**

* Validation errors with missing required fields
* Authentication failures with invalid tokens
* Server errors with proper retry logic
* Business logic errors with appropriate recovery
* Network timeouts and connection failures
* Rate limiting and backoff behavior

**Testing strategies:**

* Mock API responses for different error codes
* Simulate network failures and timeouts
* Test retry logic with controlled delays
* Validate user experience during errors
* Monitor error logging and metrics

## Next steps

#### [Sandbox to production](/api-guide/getting-started/sandbox-to-production)

Prepare your error handling for production deployment

#### [Webhooks](/api-guide/webhooks)

Configure real-time error notifications via webhooks