Skip to content

Error Handling

This guide explains how Pocketbook API handles errors, including error response formats, status codes, and best practices for error handling in your application.

Error Response Format

All API errors follow a consistent JSON structure:

json
{
  "error": {
    "type": "invalid_request_error",
    "code": "parameter_missing",
    "message": "Missing required parameter: email",
    "param": "email",
    "request_id": "req_abc123xyz"
  }
}

Error Object Fields:

  • type: Category of error (see Error Types below)
  • code: Specific error code for programmatic handling
  • message: Human-readable error description
  • param (optional): Parameter that caused the error
  • request_id: Unique request identifier for support and debugging

HTTP Status Codes

Pocketbook API uses standard HTTP status codes:

Success Codes (2xx)

  • 200 OK - Request succeeded
  • 201 Created - Resource successfully created
  • 204 No Content - Request succeeded with no response body

Client Error Codes (4xx)

  • 400 Bad Request - Invalid request parameters or malformed JSON
  • 401 Unauthorized - Missing or invalid API key
  • 402 Payment Required - Payment method required or insufficient funds
  • 403 Forbidden - Authenticated but not authorized for this resource
  • 404 Not Found - Resource does not exist
  • 405 Method Not Allowed - HTTP method not supported for this endpoint
  • 409 Conflict - Request conflicts with existing resource state
  • 422 Unprocessable Entity - Valid request but semantic errors
  • 429 Too Many Requests - Rate limit exceeded

Server Error Codes (5xx)

  • 500 Internal Server Error - Unexpected error on Pocketbook's side
  • 502 Bad Gateway - Invalid response from upstream server
  • 503 Service Unavailable - Service temporarily unavailable
  • 504 Gateway Timeout - Request timeout

Error Types

authentication_error

Authentication failed due to invalid or missing API credentials.

Example:

json
{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "Invalid API key provided",
    "request_id": "req_123"
  }
}

Common Codes:

  • invalid_api_key - API key is invalid or has been revoked
  • missing_api_key - No API key provided in request
  • expired_api_key - API key has expired

invalid_request_error

Request is malformed, missing required parameters, or contains invalid values.

Example:

json
{
  "error": {
    "type": "invalid_request_error",
    "code": "parameter_invalid",
    "message": "Amount must be a positive integer",
    "param": "amount",
    "request_id": "req_456"
  }
}

Common Codes:

  • parameter_missing - Required parameter not provided
  • parameter_invalid - Parameter has invalid value or format
  • parameter_unknown - Unknown parameter provided
  • malformed_json - Request body is not valid JSON

rate_limit_error

Too many requests in a given time period.

Example:

json
{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Retry after 60 seconds",
    "retry_after": 60,
    "request_id": "req_789"
  }
}

See Rate Limiting for details.

resource_error

Error related to a specific resource.

Example:

json
{
  "error": {
    "type": "resource_error",
    "code": "resource_not_found",
    "message": "No transaction found with ID: txn_123",
    "resource": "transaction",
    "resource_id": "txn_123",
    "request_id": "req_abc"
  }
}

Common Codes:

  • resource_not_found - Resource does not exist
  • resource_already_exists - Resource with this identifier already exists
  • resource_locked - Resource is locked and cannot be modified
  • resource_deleted - Resource has been deleted

permission_error

Authenticated user lacks permission for the requested operation.

Example:

json
{
  "error": {
    "type": "permission_error",
    "code": "insufficient_permissions",
    "message": "You do not have permission to delete this resource",
    "required_permission": "transactions.delete",
    "request_id": "req_def"
  }
}

validation_error

Request data failed validation.

Example:

json
{
  "error": {
    "type": "validation_error",
    "code": "validation_failed",
    "message": "Validation failed",
    "errors": [
      {
        "field": "email",
        "message": "Email format is invalid"
      },
      {
        "field": "amount",
        "message": "Amount must be at least 100"
      }
    ],
    "request_id": "req_ghi"
  }
}

payment_error

Payment processing failed.

Example:

json
{
  "error": {
    "type": "payment_error",
    "code": "card_declined",
    "message": "Your card was declined",
    "decline_code": "insufficient_funds",
    "payment_id": "pay_123",
    "request_id": "req_jkl"
  }
}

Common Codes:

  • card_declined - Card was declined by issuer
  • insufficient_funds - Insufficient funds in account
  • payment_method_invalid - Payment method is invalid or expired
  • processing_error - Error processing payment

api_error

Unexpected error occurred on Pocketbook's servers.

Example:

json
{
  "error": {
    "type": "api_error",
    "code": "internal_error",
    "message": "An unexpected error occurred. Please try again",
    "request_id": "req_mno"
  }
}

Error Codes Reference

Authentication Errors

CodeDescription
invalid_api_keyAPI key is invalid or revoked
missing_api_keyNo API key provided
expired_api_keyAPI key has expired
invalid_tokenJWT token is invalid or expired

Request Errors

CodeDescription
parameter_missingRequired parameter not provided
parameter_invalidParameter value is invalid
parameter_unknownUnknown parameter provided
malformed_jsonRequest body is not valid JSON
invalid_content_typeContent-Type header is invalid

Resource Errors

CodeDescription
resource_not_foundResource does not exist
resource_already_existsResource already exists
resource_lockedResource is locked
resource_deletedResource has been deleted

Payment Errors

CodeDescription
card_declinedCard was declined
insufficient_fundsInsufficient funds
payment_method_invalidInvalid payment method
processing_errorPayment processing error

Rate Limiting Errors

CodeDescription
rate_limit_exceededToo many requests
concurrent_limit_exceededToo many concurrent requests

Best Practices

1. Handle Errors Gracefully

Always check response status codes and handle errors appropriately:

javascript
try {
  const response = await fetch('https://api.pocketbook.studio/api/v1/transactions', {
    headers: { 'Authorization': `Bearer ${apiKey}` }
  });

  if (!response.ok) {
    const error = await response.json();
    handleApiError(error);
    return;
  }

  const data = await response.json();
  // Process successful response
} catch (err) {
  // Handle network errors
  console.error('Network error:', err);
}

2. Implement Retry Logic

Retry transient errors with exponential backoff:

javascript
async function apiRequest(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);

      // Don't retry client errors (4xx)
      if (response.status >= 400 && response.status < 500) {
        throw await response.json();
      }

      // Retry server errors (5xx)
      if (response.status >= 500 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000; // Exponential backoff
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }

      return await response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
    }
  }
}

3. Log Request IDs

Always log the request_id from error responses for troubleshooting:

javascript
function handleApiError(error) {
  console.error('API Error:', {
    type: error.error.type,
    code: error.error.code,
    message: error.error.message,
    requestId: error.error.request_id
  });

  // Show user-friendly message
  showUserError(getUserFriendlyMessage(error));
}

4. Validate Input Before Sending

Validate user input client-side to reduce API errors:

javascript
function validateTransactionRequest(data) {
  const errors = [];

  if (!data.amount || data.amount < 100) {
    errors.push({ field: 'amount', message: 'Amount must be at least $1.00' });
  }

  if (!data.currency || !/^[A-Z]{3}$/.test(data.currency)) {
    errors.push({ field: 'currency', message: 'Invalid currency code' });
  }

  return errors;
}

5. Handle Rate Limits

Respect rate limits and implement proper backoff:

javascript
async function handleRateLimit(response) {
  if (response.status === 429) {
    const error = await response.json();
    const retryAfter = error.error.retry_after || 60;

    console.warn(`Rate limited. Retrying after ${retryAfter} seconds`);
    await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));

    // Retry request
    return apiRequest(url, options);
  }
}

6. Provide User-Friendly Messages

Convert technical errors to user-friendly messages:

javascript
function getUserFriendlyMessage(error) {
  const errorMap = {
    'parameter_missing': 'Please fill in all required fields',
    'parameter_invalid': 'Please check your input and try again',
    'card_declined': 'Your payment was declined. Please try a different card',
    'insufficient_funds': 'Insufficient funds. Please add funds or try another payment method',
    'rate_limit_exceeded': 'Too many requests. Please wait a moment and try again'
  };

  return errorMap[error.error.code] || 'An unexpected error occurred. Please try again';
}

Testing Error Scenarios

Use test mode to simulate different error conditions:

Invalid API Key

bash
curl -X GET "https://api.pocketbook.studio/api/v1/transactions" \
  -H "Authorization: Bearer invalid_key"

Missing Parameter

bash
curl -X POST "https://api.pocketbook.studio/api/v1/transactions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

Invalid Resource ID

bash
curl -X GET "https://api.pocketbook.studio/api/v1/transactions/invalid_id" \
  -H "Authorization: Bearer YOUR_API_KEY"

Support

When contacting support about API errors:

  1. Include the request_id from the error response
  2. Provide the timestamp when the error occurred
  3. Share the request details (endpoint, method, parameters)
  4. Describe expected vs actual behavior

Contact support at support@pocketbook.studio or through the support portal.

Released under the MIT License.