Error Handling

Understanding and handling API errors.

The Bitrefill API uses standard HTTP status codes and provides detailed error messages. This guide explains how to handle errors effectively.

Error Response Format

Error responses follow this structure:

{
  "meta": {
    "_endpoint": "/invoices"
  },
  "message": "Human-readable error description",
  "error_code": "machine_readable_code"
}
  • message — Explains what went wrong
  • error_code — Consistent code for programmatic handling

HTTP Status Codes

CodeMeaningCommon Causes
400Bad RequestInvalid parameters
401UnauthorizedMissing or invalid auth
403ForbiddenInsufficient permissions
404Not FoundResource doesn't exist
429Too Many RequestsRate limit exceeded
500Server ErrorInternal error

Handling Errors

async function apiRequest(url, options) {
  const response = await fetch(url, options);
  const data = await response.json();
  
  if (!response.ok) {
    const error = new Error(data.message || 'API Error');
    error.code = data.error_code;
    error.status = response.status;
    throw error;
  }
  
  return data;
}

// Usage
try {
  const invoice = await apiRequest('/invoices', { method: 'POST', ... });
} catch (error) {
  switch (error.code) {
    case 'balance_too_low':
      console.log('Need to add balance');
      break;
    case 'out_of_stock':
      console.log('Product unavailable');
      break;
    default:
      console.log(`Error: ${error.message}`);
  }
}

Error Guides

Quick Reference

Authentication Errors

CodeMessageSolution
401UnauthorizedCheck API credentials
403ForbiddenVerify account permissions

Invoice Errors

Error CodeMessageSolution
balance_too_lowInsufficient balanceAdd funds
out_of_stockProduct unavailableTry different product
not_foundProduct doesn't existCheck product ID
invalid_paramInvalid parameterCheck request format
too_many_itemsToo many itemsMax 20 per invoice

Rate Limit Errors

CodeMessageSolution
429Rate limit exceededWait and retry

Check X-RateLimit-Reset header for when to retry.