DocsAPI ReferenceError Handling

Error Handling

Learn how to handle errors from the Quality QR API gracefully.

Error Response Format

All errors follow a consistent JSON structure:

Error Response
{
  "success": false,
  "error": {
    "code": "invalid_api_key",
    "message": "The API key provided is invalid or has been revoked.",
    "details": null
  }
}
FieldTypeDescription
successbooleanAlways false for errors
error.codestringMachine-readable error code
error.messagestringHuman-readable error description
error.detailsobject | nullAdditional error context (e.g., field-specific errors)

Validation Errors

When validation fails, the details field contains specific field errors:

Validation Error Response
{
  "success": false,
  "error": {
    "code": "validation_error",
    "message": "Request validation failed",
    "details": {
      "fields": {
        "content": "Content is required",
        "type": "Invalid QR code type"
      }
    }
  }
}

Error Codes Reference

Complete list of error codes you may encounter:

StatusCodeDescriptionResolution
400bad_requestThe request body is invalid or missing required fields.Check the request body matches the expected schema.
400invalid_typeThe QR code type is not supported.Use a valid type: url, text, email, phone, sms, wifi, vcard, or event.
400invalid_contentThe content is invalid for the specified QR code type.Ensure the content matches the type (e.g., valid URL for 'url' type).
400content_too_longThe content exceeds the maximum length for QR codes.Reduce the content length or use a dynamic QR code with a short URL.
401missing_api_keyNo Authorization header was provided.Include the Authorization header with your API key.
401invalid_api_keyThe API key is invalid or has been revoked.Check your API key is correct or generate a new one.
401expired_api_keyThe API key has expired.Generate a new API key from your dashboard.
403forbiddenYou don't have permission to perform this action.Check your plan limits or upgrade to access this feature.
404not_foundThe requested resource was not found.Verify the resource ID is correct.
409conflictA resource with this identifier already exists.Use a different identifier or update the existing resource.
422validation_errorThe request failed validation.Check the error details for specific field issues.
429rate_limit_exceededYou've exceeded your rate limit.Wait and retry, or upgrade your plan for higher limits.
500internal_errorAn unexpected error occurred on our servers.Retry the request. If it persists, contact support.
503service_unavailableThe service is temporarily unavailable.Wait and retry the request.

Handling Errors in Code

Here's how to properly handle API errors in your application:

JavaScript
async function createQRCode(content) {
  try {
    const response = await fetch('https://quality-qr.app/api/v1/qr', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.QUALITY_QR_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ type: 'url', content }),
    });

    const data = await response.json();

    if (!response.ok) {
      // Handle specific error codes
      switch (data.error?.code) {
        case 'rate_limit_exceeded':
          // Wait and retry
          await sleep(60000);
          return createQRCode(content);
        case 'invalid_api_key':
          throw new Error('Please check your API key');
        case 'validation_error':
          console.error('Validation errors:', data.error.details);
          throw new Error(data.error.message);
        default:
          throw new Error(data.error?.message || 'Unknown error');
      }
    }

    return data;
  } catch (error) {
    console.error('QR generation failed:', error);
    throw error;
  }
}
Python
import requests
import time
import os

class QualityQRError(Exception):
    def __init__(self, code, message, details=None):
        self.code = code
        self.message = message
        self.details = details
        super().__init__(message)

def create_qr_code(content, retries=3):
    for attempt in range(retries):
        response = requests.post(
            'https://quality-qr.app/api/v1/qr',
            headers={
                'Authorization': f'Bearer {os.environ["QUALITY_QR_API_KEY"]}',
                'Content-Type': 'application/json',
            },
            json={'type': 'url', 'content': content}
        )

        data = response.json()

        if response.ok:
            return data

        error = data.get('error', {})
        code = error.get('code')

        if code == 'rate_limit_exceeded' and attempt < retries - 1:
            time.sleep(60)
            continue

        raise QualityQRError(
            code=code,
            message=error.get('message', 'Unknown error'),
            details=error.get('details')
        )

Best Practices

Always check the response status

Don't assume requests succeed. Always check the HTTP status code and success field.

Implement retry logic for transient errors

Errors like 429 (rate limit) and 503 (service unavailable) are often temporary. Implement exponential backoff for retries.

Log error codes for debugging

Store the error.code in your logs to help diagnose issues later.

Don't expose error details to end users

API error messages may contain technical details. Show user-friendly messages in your UI instead.