Documentation / Getting Started

Error Handling

5 min read

This guide explains the error responses you may receive from the MailingAPI and how to handle them properly.

Error Response Format

Every error follows the same JSON format:

{
  "error": {
    "code": "validation_failed",
    "message": "Błąd walidacji",
    "details": {
      "subject": ["can't be blank"]
    }
  }
}

Fields:

  • code — Stable, machine-readable error code. Branch on code in your integration.
  • message — Human-readable description. It is meant for logs and people, may be in Polish for some errors and may change over time — never branch on message.
  • details — Present only for validation_failed. A map of field name to a list of messages.
  • retry_after — Present only on 429. Integer, in seconds.

HTTP Status Codes

Code Meaning When it happens
200 OK Request succeeded
201 Created Resource created
202 Accepted Async operation queued
400 Bad Request Malformed request
401 Unauthorized Missing or invalid API key
403 Forbidden Valid key, but the action is not allowed
404 Not Found Resource doesn’t exist
409 Conflict Resource already exists, or an idempotent request is still processing
413 Payload Too Large Request body exceeds 25 MB
422 Unprocessable Field validation failed, or idempotency key reused
429 Too Many Requests Rate or sending limit exceeded
500 Server Error Something went wrong on our end

Error Codes

HTTP code Meaning Retry?
400 bad_request Malformed request, e.g. invalid sender address, batch over 1000 messages, missing messages / recipient_variables No
400 invalid_idempotency_key Idempotency-Key is empty or longer than 255 characters No
401 missing_auth, invalid_auth, invalid_key, insufficient_permissions, ip_not_allowed Authentication or permission problem No
403 forbidden E.g. the sender is not from the API key’s domain No
403 organization_not_active, domain_not_verified, api_key_without_domain, daily_limit_reached, monthly_limit_reached, ip_blocked Account or plan state No — fix the account state first
404 not_found Resource doesn’t exist No
409 idempotency_request_in_progress The first request with the same Idempotency-Key is still processing Yes, after Retry-After seconds
409 conflict Resource already exists (e.g. account signup with an existing email) No
422 validation_failed Field validation failed, see details No
422 idempotency_key_reused The same key was used with a different request body No
429 rate_limit_exceeded Per-second / per-minute API limit Yes, after Retry-After seconds
429 daily_limit_exceeded Daily send limit of the domain; retry_after = seconds until UTC midnight Yes, after Retry-After seconds
429 recipient_rate_limited Max 10 emails per hour and 50 per day to the same recipient per organization; retry_after = seconds until the next full hour (hourly limit) or UTC midnight (daily limit) Yes, after Retry-After seconds
500 internal_error Something went wrong on our end Yes, with exponential backoff; reuse the same Idempotency-Key

Authentication and permission errors (401, 403)

{"error": {"code": "invalid_key", "message": "Invalid API key"}}

Fix: Check that your API key is correct, active, has the required permission and that the from address belongs to the key’s domain.

Validation errors (422)

{
  "error": {
    "code": "validation_failed",
    "message": "Błąd walidacji",
    "details": {
      "to": ["can't be blank"],
      "subject": ["should be at most 998 character(s)"]
    }
  }
}

Fix: Check the details object and correct each field.

Rate limit errors (429)

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded",
    "retry_after": 5
  }
}

Every 429 response carries the standard Retry-After header (integer seconds) and retry_after in the body, with the same value. Prefer the Retry-After header. Per-second and per-minute 429 responses also include the X-RateLimit-* headers; daily-limit 429 responses include X-Daily-Limit and X-Daily-Remaining: 0. See API Overview → Rate limiting.

Fix: Wait Retry-After seconds, then retry.

Resource errors (404, 409)

{"error": {"code": "not_found", "message": "Message not found"}}

Fix: Verify the resource ID or check for duplicates.

Handling Errors in Code

Python

import requests
from requests.exceptions import HTTPError

try:
    response = requests.post(
        "https://api.mailingapi.com/v1/messages/send",
        headers={"Authorization": f"Bearer {api_key}"},
        json=payload
    )
    response.raise_for_status()
    result = response.json()

except HTTPError as e:
    error = e.response.json().get("error", {})

    if e.response.status_code == 401:
        # Re-authenticate or check API key
        handle_auth_error()
    elif e.response.status_code == 429:
        # Respect rate limit: Retry-After header, in seconds
        retry_after = int(e.response.headers.get("Retry-After", 60))
        time.sleep(retry_after)
        # Retry request
    elif e.response.status_code == 422:
        # Log validation errors (branch on error["code"], not on the message)
        logger.error(f"Validation failed: {error}")
    else:
        # Unexpected error
        logger.error(f"API error: {error}")
        raise

JavaScript

async function sendEmail(payload) {
  try {
    const response = await fetch('https://api.mailingapi.com/v1/messages/send', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    });

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

      switch (response.status) {
        case 401:
          throw new AuthenticationError(error.message);
        case 429:
          // Retry-After header is in seconds
          const retryAfter = Number(response.headers.get('Retry-After')) || 60;
          await sleep(retryAfter * 1000);
          return sendEmail(payload); // Retry
        case 422:
          throw new ValidationError(error.code, error.details);
        default:
          throw new APIError(error.message, error.code);
      }
    }

    return response.json();

  } catch (error) {
    console.error('Failed to send email:', error);
    throw error;
  }
}

Retry Strategy

For transient errors (500, 502, 503, 504), implement exponential backoff. For 429 and 409 idempotency_request_in_progress, wait the number of seconds given in the Retry-After header instead:

import time
import random

def send_with_retry(payload, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = send_email(payload)
            return response
        except TransientError as e:
            if attempt == max_retries - 1:
                raise

            # Exponential backoff with jitter
            delay = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)

Do:

  • Retry on 429 and 409 idempotency_request_in_progress after Retry-After seconds
  • Retry on 500, 502, 503, 504 with exponential backoff, reusing the same Idempotency-Key
  • Use exponential backoff
  • Add random jitter to prevent thundering herd
  • Set a maximum retry count

Don’t:

  • Retry on 400, 401, 403, 404, 409 conflict, 422 — these won’t change until you change the request or the account state
  • Retry immediately without delay
  • Retry indefinitely

Idempotency

For safe retries, use idempotency keys:

curl -X POST https://api.mailingapi.com/v1/messages/send \
  -H "Authorization: Bearer $API_KEY" \
  -H "Idempotency-Key: unique-request-id-123" \
  -H "Content-Type: application/json" \
  -d '{...}'

If you retry with the same Idempotency-Key, you’ll get the original response (with header Idempotent-Replayed: true) instead of creating a duplicate. Generate the key once per logical request and reuse it for every retry of that request.

Idempotency errors:

Status error.code Meaning Retry?
409 idempotency_request_in_progress The first request with this key is still being processed Yes, after Retry-After seconds
422 idempotency_key_reused The key was already used with a different request body No — use a new key
400 invalid_idempotency_key The key is empty or longer than 255 characters No

See API Overview → Idempotency for the full rules.

Debugging Tips

  1. Read the error code and details — The code is stable and machine-readable; message is a human-readable explanation
  2. Check request logs — In your dashboard under Logs → API Requests
  3. Validate locally — Use /v1/messages/analyze to check content before sending

Getting Help

If you’re stuck:

  • Search the API Reference (interactive, requires JavaScript) or use the OpenAPI 3 spec at /api/openapi for endpoint details
  • Contact support@mailingapi.com with:
    • Request ID (from response headers)
    • Error code and message
    • Minimal reproduction example

Next steps

Now you understand how to handle errors. Learn about sending emails in detail.

Sending emails →