Error Handling

This guide covers how to handle errors when integrating with the Yugo API.

HTTP Status Codes

The Yugo API uses standard HTTP status codes to indicate success or failure:

CodeMeaningDescription
200SuccessRequest completed successfully
400Bad RequestInvalid request parameters
401UnauthorizedMissing or invalid API key
403ForbiddenAPI key lacks required permissions
404Not FoundResource doesn't exist
422Unprocessable EntityRequest validation failed
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error

Error Response Format

Error responses include details to help diagnose the issue:

json
{
  "error": {
    "code": "invalid_parameter",
    "message": "The amount must be at least 2",
    "param": "amount"
  }
}
FieldDescription
codeMachine-readable error code
messageHuman-readable error description
paramThe parameter that caused the error (if applicable)

Common Errors

Authentication Errors

Missing API Key

json
{
  "error": {
    "code": "authentication_required",
    "message": "API key is required"
  }
}

Invalid API Key

json
{
  "error": {
    "code": "invalid_api_key",
    "message": "The provided API key is invalid"
  }
}

Validation Errors

Invalid Amount

json
{
  "error": {
    "code": "invalid_parameter",
    "message": "Amount must be at least 2 with max 2 decimal places",
    "param": "amount"
  }
}

Missing Required Field

json
{
  "error": {
    "code": "missing_parameter",
    "message": "The 'names' field is required",
    "param": "names"
  }
}

Transaction Errors

Transaction Not Found

json
{
  "error": {
    "code": "resource_not_found",
    "message": "Transaction not found"
  }
}

Payment Status Errors

A2A Payments

StatusMeaningAction
FAILED_INTENTAuthorization failed or rejected by bankPrompt user to retry or use different payment method

Merchant On-ramp

StatusMeaningAction
FAILED_INTENTAuthorization failed or rejectedPrompt user to retry
Bank Deposit FAILEDBank deposit failed or timed outContact support

Handling Errors in Code

Node.js

javascript
async function createPayment(paymentData) {
  try {
    const response = await fetch('https://api.yugo.finance/transaction/create-bank-transfer', {
      method: 'POST',
      headers: {
        'x-api-key': process.env.YUGO_API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(paymentData)
    });

    if (!response.ok) {
      const error = await response.json();
      
      switch (response.status) {
        case 401:
          throw new Error('Invalid API key');
        case 400:
        case 422:
          throw new Error(`Validation error: ${error.error.message}`);
        case 429:
          // Implement retry with backoff
          await sleep(1000);
          return createPayment(paymentData);
        default:
          throw new Error(`API error: ${error.error.message}`);
      }
    }

    return await response.json();
  } catch (error) {
    console.error('Payment creation failed:', error);
    throw error;
  }
}

Python

python
import requests
import time

def create_payment(payment_data):
    try:
        response = requests.post(
            'https://api.yugo.finance/transaction/create-bank-transfer',
            headers={
                'x-api-key': os.environ['YUGO_API_KEY'],
                'Content-Type': 'application/json'
            },
            json=payment_data
        )
        
        if response.status_code == 401:
            raise Exception('Invalid API key')
        elif response.status_code in [400, 422]:
            error = response.json()
            raise Exception(f"Validation error: {error['error']['message']}")
        elif response.status_code == 429:
            time.sleep(1)
            return create_payment(payment_data)
        elif not response.ok:
            error = response.json()
            raise Exception(f"API error: {error['error']['message']}")
        
        return response.json()
    
    except requests.RequestException as e:
        print(f'Payment creation failed: {e}')
        raise

Best Practices

1. Always Check Response Status

Never assume a request succeeded. Always check the HTTP status code.

2. Log Errors

Log error details for debugging:

javascript
if (!response.ok) {
  const error = await response.json();
  console.error('API Error:', {
    status: response.status,
    code: error.error.code,
    message: error.error.message,
    param: error.error.param
  });
}

3. Implement Retry Logic

For transient errors (5xx, 429), implement exponential backoff:

javascript
async function withRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

4. Handle User-Facing Errors Gracefully

Don't expose raw API errors to users:

javascript
function getUserFriendlyMessage(error) {
  switch (error.code) {
    case 'invalid_parameter':
      return 'Please check your payment details and try again.';
    case 'authentication_required':
      return 'There was a problem processing your payment. Please try again.';
    default:
      return 'Something went wrong. Please try again later.';
  }
}

5. Verify Transaction Status

After any error, verify the actual transaction status via API before taking action:

javascript
async function handlePaymentError(transactionId, error) {
  // Check actual status before assuming failure
  const transaction = await getTransaction(transactionId);
  
  if (transaction.paymentStatus === 'AUTHORIZED') {
    // Payment actually succeeded
    return handleSuccess(transaction);
  }
  
  // Handle actual failure
  return handleFailure(error);
}
Was this page helpful?