When working with the Straddle API, it’s crucial to properly handle HTTP errors to ensure your application can gracefully manage unexpected situations. This guide will walk you through the different types of errors you might encounter, how to interpret them, and best practices for error handling.

Common HTTP Errors

Here’s a quick reference table of common HTTP errors you might encounter when using the Straddle API:

Status CodeError TypeDescriptionCommon Causes
400Bad RequestThe request was unacceptable, often due to missing a required parameter.
  • Missing required fields
  • Invalid field values
  • Malformed JSON
401UnauthorizedNo valid API key provided.
  • Invalid API key
  • Expired API key
403ForbiddenThe API key doesn’t have permissions to perform the request.
  • Insufficient permissions
  • Incorrect account access
404Not FoundThe requested resource doesn’t exist.
  • Incorrect resource ID
  • Deleted resource
422Unprocessable EntityThe request was well-formed but was unable to be followed due to semantic errors.
  • Invalid parameter values
  • Logical errors in request
429Too Many RequestsToo many requests hit the API too quickly.
  • Exceeding rate limits
500Internal Server ErrorSomething went wrong on Straddle’s end.
  • Unexpected server issues

Understanding HTTP Status Codes

Straddle uses standard HTTP status codes to indicate the success or failure of an API request. Here are the main categories:

  • 2xx: Success
  • 4xx: Client errors
  • 5xx: Server errors

Common Error Responses

When an error occurs, Straddle returns a JSON object with details about the error. The structure of this object is consistent across all error types:

{
  "error": {
    "code": "error_code",
    "message": "A human-readable message providing more details about the error.",
    "type": "error_type"
  }
}

Types of Errors

400 Bad Request

This error occurs when the request is malformed or contains invalid parameters.

Example response:

{
  "error": {
    "code": "invalid_request_error",
    "message": "The 'amount' parameter is required and must be a positive integer.",
    "type": "invalid_request_error"
  }
}

How to handle:

  • Check your request parameters for any missing or invalid values.
  • Ensure all required fields are included and formatted correctly.

401 Unauthorized

This error occurs when authentication fails, typically due to an invalid API key.

Example response:

{
  "error": {
    "code": "invalid_api_key",
    "message": "The provided API key is invalid or has been revoked.",
    "type": "authentication_error"
  }
}

How to handle:

  • Verify that you’re using the correct API key.
  • Check if your API key has been revoked or expired.
  • Ensure you’re using the correct environment (test vs. production).

403 Forbidden

This error occurs when the authenticated user doesn’t have permission to perform the requested action.

Example response:

{
  "error": {
    "code": "permission_denied",
    "message": "You don't have permission to access this resource.",
    "type": "authentication_error"
  }
}

How to handle:

  • Check if the authenticated account has the necessary permissions.
  • If you’re using a platform account, ensure you’ve correctly specified the Straddle-Account-Id header.

404 Not Found

This error occurs when the requested resource doesn’t exist.

Example response:

{
  "error": {
    "code": "resource_missing",
    "message": "The requested resource does not exist.",
    "type": "invalid_request_error"
  }
}

How to handle:

  • Verify that you’re using the correct resource ID.
  • Check if the resource has been deleted or hasn’t been created yet.

422 Unprocessable Entity

This error occurs when the request is well-formed, but contains invalid data.

Example response:

{
  "error": {
    "code": "invalid_parameter",
    "message": "The 'amount' parameter must be greater than 0.",
    "type": "invalid_request_error"
  }
}

How to handle:

  • Review the error message for specific details about which parameter is invalid.
  • Adjust your request data accordingly.

429 Too Many Requests

This error occurs when you’ve exceeded the rate limit for API requests.

Example response:

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "You have exceeded the rate limit. Please try again later.",
    "type": "rate_limit_error"
  }
}

How to handle:

  • Implement exponential backoff and retry logic in your application.
  • Consider optimizing your code to make fewer API requests.

500 Internal Server Error

This error indicates an unexpected condition on the server side.

Example response:

{
  "error": {
    "code": "internal_server_error",
    "message": "An unexpected error occurred. Please try again later.",
    "type": "api_error"
  }
}

How to handle:

  • Implement a retry mechanism with exponential backoff.
  • If the error persists, contact Straddle support and provide the Request-Id and Correlation-Id.

Best Practices for Error Handling

  1. Always check the HTTP status code: Don’t assume a request was successful. Always check the HTTP status code before processing the response.

  2. Parse the error response: Extract the error details from the JSON response to get more information about what went wrong.

  3. Log errors with context: When logging errors, include relevant context such as the Request-Id, Correlation-Id, and any pertinent request details.

  4. Implement retry logic: For transient errors (like rate limiting or temporary server issues), implement a retry mechanism with exponential backoff.

  5. Provide meaningful error messages to users: Translate API errors into user-friendly messages in your application’s UI.

  6. Monitor error rates: Keep track of the frequency and types of errors you’re encountering to identify and address recurring issues.

Example: Error Handling in Node.js

Here’s an example of how you might handle errors when making a request to the Straddle API:

const Straddle = require('straddle');
const straddle = new Straddle('sk_test_51NBBbbDBkrcnHrnR0nBGsOvFHQrM0n8T1FKZmAUWbJqq8oRsAM3dEZzBIbHwzKrVUUFOyRvX1Ib8Sn3VWWQMW00r300IIrGBWb1');

async function createCharge(amount, currency, paykey) {
  try {
    const charge = await straddle.charges.create({
      amount,
      currency,
      paykey,
      payment_date: new Date().toISOString().split('T')[0],
      consent_type: 'internet'
    });
    return charge;
  } catch (error) {
    if (error.statusCode === 400) {
      console.error('Invalid request:', error.message);
    } else if (error.statusCode === 401) {
      console.error('Authentication failed:', error.message);
    } else if (error.statusCode === 429) {
      console.error('Rate limit exceeded. Retrying in 5 seconds...');
      await new Promise(resolve => setTimeout(resolve, 5000));
      return createCharge(amount, currency, paykey);
    } else {
      console.error('An unexpected error occurred:', error.message);
    }
    throw error;
  }
}

createCharge(1000, 'usd', 'pk_test_TYooMQauvdEDq54NiTphI7jx')
  .then(charge => console.log('Charge created:', charge.id))
  .catch(error => console.error('Failed to create charge:', error));

This example demonstrates how to catch and handle different types of errors, including implementing a simple retry mechanism for rate limiting errors.

Conclusion

Proper error handling is crucial for building robust applications that integrate with the Straddle API. By understanding the different types of errors, implementing appropriate error handling strategies, and following best practices, you can create a smoother experience for your users and more easily diagnose and resolve issues when they arise.

Remember to always refer to the API Reference documentation for the most up-to-date information on error codes and handling for specific endpoints.