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

# Error Handling

> Error codes and troubleshooting for Rise B2B API

# Error Handling

Rise B2B API returns clear error codes and messages for all endpoints. This guide helps you understand and handle errors effectively in your integrations.

<CardGroup cols={2}>
  <Card title="Authentication Errors" icon="key">
    Common authentication and authorization issues
  </Card>

  <Card title="API Errors" icon="triangle-exclamation">
    HTTP status codes and API-specific errors
  </Card>

  <Card title="SDK Errors" icon="code">
    SDK-specific error handling and troubleshooting
  </Card>

  <Card title="Best Practices" icon="shield">
    Error handling best practices and patterns
  </Card>
</CardGroup>

## Common Error Codes

| HTTP Status | Description           | Common Causes                              |
| ----------- | --------------------- | ------------------------------------------ |
| `400`       | Bad Request           | Missing or invalid parameters              |
| `401`       | Unauthorized          | Invalid JWT token or SIWE signature        |
| `403`       | Forbidden             | Insufficient permissions for the operation |
| `404`       | Not Found             | Resource doesn't exist                     |
| `429`       | Too Many Requests     | Rate limit exceeded                        |
| `500`       | Internal Server Error | Server-side error                          |

## Authentication Errors

### SIWE Authentication Errors

| Error                                  | Cause                         | Solution                                                                      |
| -------------------------------------- | ----------------------------- | ----------------------------------------------------------------------------- |
| `Rise ID and private key are required` | Missing SIWE credentials      | Configure `RISE_ID` and `WALLET_PRIVATE_KEY` in environment, or use JWT token |
| `Invalid Rise ID address`              | Incorrect Rise ID format      | Ensure Rise ID starts with 0x and is 42 characters                            |
| `Invalid private key`                  | Incorrect private key format  | Ensure private key starts with 0x and is 66 characters                        |
| `JWT generation failed`                | Authentication failed         | Verify your Rise ID and private key match your Rise account                   |
| `SIWE error: Invalid signature`        | Signature verification failed | Verify you're using the correct wallet and signing the exact message          |
| `SIWE error: Expired nonce`            | Nonce has expired             | Retrieve a new SIWE message and sign it immediately                           |

### JWT Authentication Errors

| Error                               | Cause                        | Solution                                         |
| ----------------------------------- | ---------------------------- | ------------------------------------------------ |
| `401 Unauthorized`                  | JWT token expired or invalid | Refresh your JWT token or re-authenticate        |
| `Invalid JWT format`                | Malformed JWT token          | Verify JWT token format and ensure it's complete |
| `JWT signature verification failed` | Token has been tampered with | Retrieve a new JWT token from Rise               |

## API Errors

### Common API Error Responses

| Error                   | Cause                      | Solution                                         |
| ----------------------- | -------------------------- | ------------------------------------------------ |
| `401 Unauthorized`      | Your JWT token has expired | SDK will auto-refresh, or manually refresh token |
| `403 Forbidden`         | Insufficient permissions   | Verify your role permissions for the operation   |
| `404 Not Found`         | Resource doesn't exist     | Verify the nanoid or resource identifier         |
| `400 Bad Request`       | Invalid request parameters | Verify all required fields and parameter formats |
| `429 Too Many Requests` | Rate limit exceeded        | Implement exponential backoff and retry later    |

### Resource-Specific Errors

| Error               | Cause                                      | Solution                                      |
| ------------------- | ------------------------------------------ | --------------------------------------------- |
| `Team not found`    | Invalid team nanoid                        | Verify the team exists and you have access    |
| `Company not found` | Invalid company nanoid                     | Verify company permissions and nanoid         |
| `User not found`    | Invalid user nanoid                        | Verify user exists in your organization       |
| `Payment failed`    | Insufficient balance or invalid parameters | Verify balance and payment parameters         |
| `Invalid currency`  | Unsupported currency code                  | Use supported currency codes (USD, EUR, etc.) |

## SDK Error Handling

### SDK-Specific Errors

```javascript theme={null}
const { RiseApiClient } = require('@riseworks/riseworks-sdk');

async function handleSDKErrors() {
  try {
    const client = new RiseApiClient({
      environment: 'prod',
      riseIdAuth: {
        riseId: riseId,
        privateKey: walletPrivateKey
      }
    });

    const user = await client.me.get();
    console.log('Success:', user.data);

  } catch (error) {
    // SDK-specific error handling
    if (error.message.includes('Rise ID and private key are required')) {
      console.error('Missing credentials - verify your environment variables');
    } else if (error.message.includes('Invalid Rise ID address')) {
      console.error('Invalid Rise ID format - should be 0x + 40 hex characters');
    } else if (error.message.includes('Invalid private key')) {
      console.error('Invalid private key format - should be 0x + 64 hex characters');
    } else if (error.message.includes('401')) {
      console.error('Authentication failed - verify your credentials');
    } else if (error.message.includes('403')) {
      console.error('Permission denied - verify your role permissions');
    } else if (error.message.includes('404')) {
      console.error('Resource not found - verify the nanoid');
    } else if (error.message.includes('429')) {
      console.error('Rate limit exceeded - implement backoff and retry');
    } else {
      console.error('Unexpected error:', error.message);
    }
  }
}
```

### Automatic Error Handling

The Rise SDK provides automatic error handling for common scenarios:

```javascript theme={null}
// SDK automatically handles JWT refresh
    const client = new RiseApiClient({
      riseIdAuth: {
        riseId: riseId,
        privateKey: walletPrivateKey
      }
    });

// If JWT expires, SDK automatically generates a new one
const user = await client.me.get(); // No manual error handling needed
```

## Error Handling Best Practices

### Recommended Practices:

* **Implement comprehensive error handling** for all API calls
* **Log errors with context** for debugging
* **Show user-friendly error messages** to end users
* **Implement retry logic** with exponential backoff for transient errors
* **Monitor error rates** and set up alerts
* **Use SDK error handling** when possible

### Security Considerations:

* **Never ignore errors** or catch them silently
* **Never show technical error messages** to end users
* **Never retry indefinitely** without backoff
* **Never log sensitive information** like private keys or JWT tokens
* **Never assume errors are always client-side**

### Retry Logic Example

```javascript theme={null}
async function retryWithBackoff(apiCall, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      if (attempt === maxRetries) {
        throw error; // Final attempt failed
      }

      // Don't retry on client errors (4xx)
      if (error.message.includes('400') ||
          error.message.includes('401') ||
          error.message.includes('403') ||
          error.message.includes('404')) {
        throw error;
      }

      // Exponential backoff: 1s, 2s, 4s
      const delay = Math.pow(2, attempt - 1) * 1000;
      console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

// Usage
const user = await retryWithBackoff(() => client.me.get());
```

## Monitoring and Debugging

### Error Logging

```javascript theme={null}
// Structured error logging
function logError(error, context = {}) {
  console.error({
    timestamp: new Date().toISOString(),
    error: error.message,
    status: error.status || 'unknown',
    context,
    stack: error.stack
  });
}

// Usage
try {
  await client.payments.sendPayment(paymentData);
} catch (error) {
  logError(error, {
    operation: 'sendPayment',
    teamId: paymentData.team_nanoid
  });
}
```

### Common Debugging Steps

1. **Verify Authentication**
   * Verify Rise ID and private key are correct
   * Ensure JWT token is valid and not expired
   * Verify wallet permissions for the Rise account

2. **Validate Parameters**
   * Verify all required fields are provided
   * Verify nanoid formats are correct
   * Ensure currency codes are supported

3. **Verify Permissions**
   * Verify your role has permission for the operation
   * Verify team/company access permissions
   * Ensure you're using the correct Rise account

4. **Network Issues**
   * Verify internet connectivity
   * Verify API endpoint is accessible
   * Verify rate limiting status

## Support Resources

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference">
    Full API specification with error details
  </Card>

  <Card title="Authentication Guide" icon="key" href="/authentication">
    Authentication troubleshooting
  </Card>

  <Card title="SDK Documentation" icon="book" href="/sdk/examples">
    SDK error handling examples
  </Card>

  <Card title="Support Email" icon="envelope" href="mailto:Hello@Riseworks.io">
    Get help from our team
  </Card>
</CardGroup>

<Note>
  **Need immediate assistance?** Contact our support team at [Hello@Riseworks.io](mailto:Hello@Riseworks.io) with your error details and we'll help you resolve the issue quickly.
</Note>
