> ## Documentation Index
> Fetch the complete documentation index at: https://docs.posta.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Errors

> Understanding and handling Posta API errors

The Posta API uses conventional HTTP response codes to indicate the success or failure of an API request. This guide will help you understand, handle, and troubleshoot the various error types you may encounter.

## Quick reference

<Accordion title="Common errors and solutions">
  | Error message                         | Quick solution                                                       |
  | ------------------------------------- | -------------------------------------------------------------------- |
  | Incorrect or expired API key          | Check and update your API key                                        |
  | Too many requests                     | Implement exponential backoff                                        |
  | Missing required variable in template | Check template variables and ensure all required fields are provided |
  | Image resolution too low              | Ensure images have a DPI of at least 300                             |
  | Password-protected PDF                | Remove password protection before uploading                          |
</Accordion>

<Accordion title="HTTP status code summary">
  | Code                       | Description                                                                           |
  | -------------------------- | ------------------------------------------------------------------------------------- |
  | `200`                      | OK - The request was successful                                                       |
  | `400`                      | Bad Request - The request was unacceptable, often due to missing a required parameter |
  | `401`                      | Unauthorized                                                                          |
  | `403`                      | Forbidden                                                                             |
  | `404`                      | Not Found - The requested resource doesn't exist                                      |
  | `409`                      | Conflict - The request conflicts with another request or the current state            |
  | `422`                      | Unprocessable Entity - The request was well-formed but had semantic errors            |
  | `429`                      | Too Many Requests - Rate limit exceeded                                               |
  | `500`, `502`, `503`, `504` | Server Errors - An error occurred on Posta's services                                 |
</Accordion>

## Understanding error responses

### Error response format

All API errors are returned in JSON format, conforming to the [Problem Details for HTTP APIs (RFC 7807)](https://datatracker.ietf.org/doc/html/rfc7807) standard. This format provides a consistent and machine-readable structure for error responses.

<CodeGroup>
  ```json Example error response theme={null}
  {
      "type": "https://datatracker.ietf.org/doc/html/rfc9110#section-15.5.1",
      "title": "An error occurred while processing your request",
      "status": 400,
      "detail": "Validation failed",
      "errors": {
          "recipient.individual.firstName": "firstName can not be empty"
      }
  }
  ```
</CodeGroup>

### Error response fields

<Accordion title="Error object">
  <ParamField path="type" type="string">
    A URI reference to the specification defining the error type. It points to the relevant section of the HTTP Semantics RFC.
  </ParamField>

  <ParamField path="title" type="string">
    A general, human-readable summary of the problem.
  </ParamField>

  <ParamField path="status" type="number">
    The HTTP status code for this occurrence of the problem.
  </ParamField>

  <ParamField path="detail" type="string">
    A more specific human-readable explanation of the problem.
  </ParamField>

  <ParamField path="errors" type="object">
    An object containing specific validation errors. Keys are the paths to the invalid fields, and values are descriptions of the validation failures.
  </ParamField>

  <Note>
    The `errors` object can provide detailed information about specific validation failures, allowing for precise error handling and user feedback.
  </Note>
</Accordion>

## Handling errors

Implementing robust error handling is crucial for creating reliable integrations with the Posta API. Follow these best practices to effectively manage and respond to various error scenarios:

<AccordionGroup>
  <Accordion title="1. Examine error responses">
    When receiving an error, carefully examine the `title`, `detail`, and `errors` fields to determine the appropriate action:

    Example:

    ```json theme={null}
    {
      "type": "https://datatracker.ietf.org/doc/html/rfc9110#section-15.5.1",
      "errors": {
        "recipient.individual.firstName": "firstName can not be empty"
      }
    }
    ```
  </Accordion>

  <Accordion title="2. Implement retry logic">
    For transient errors, implement a retry mechanism to improve the reliability of your integration:

    * Retry requests for 5xx status codes (except 501 Not Implemented) and 429 Too Many Requests.
    * Use exponential backoff to increase the time between retry attempts.
    * Set a maximum number of retry attempts to avoid infinite loops.
  </Accordion>

  <Accordion title="3. Handle rate limiting">
    Pay special attention to rate limit errors (status code 429):

    * Implement exponential backoff with jitter to prevent synchronized retry attempts.
    * Use response headers to track your rate limit status.
    * Consider optimizing your code to reduce the number of API calls if you frequently hit rate limits.

    Refer to our [Rate limiting](/api-reference/rate-limiting) documentation for detailed information on handling rate limits.
  </Accordion>

  <Accordion title="4. Validate input before sending">
    To minimize validation errors (status code 400):

    * Validate all required fields are present and correctly formatted before making API calls.
    * Check that values meet specified constraints (e.g., string length, numeric ranges).
    * Ensure all enumerated values (e.g., status codes, types) are valid.
  </Accordion>

  <Accordion title="5. Handle authentication errors">
    For authentication errors (status codes 401 and 403):

    * Verify that you're using the correct API key.
    * Check that your API key has the necessary permissions for the requested operation.

    If you consistently encounter authentication errors, review your [API key management](/api-reference/authentication) practices.
  </Accordion>

  <Accordion title="6. Log errors for debugging">
    Maintain detailed logs of all API interactions, especially errors:

    * Log the full error response, including all fields returned by the API.
    * Include relevant request details (endpoint, method, headers, body) in your logs.
    * Use a unique identifier for each request to correlate logs with specific API calls.
  </Accordion>

  <Accordion title="7. Provide meaningful feedback to users">
    Translate API errors into user-friendly messages in your application:

    * Use the `detail` field to provide specific information about what went wrong.
    * For validation errors, use the information in the `errors` object to highlight specific fields that need correction.
    * Avoid exposing raw error messages or stack traces to end-users.
  </Accordion>

  <Accordion title="8. Monitor and alert">
    Set up monitoring and alerting for your API integration:

    * Track error rates and types to identify recurring issues.
    * Set up alerts for critical errors or unusual error patterns.
    * Regularly review error logs to identify areas for improvement in your integration.

    Consider using application performance monitoring (APM) tools to gain insights into your API usage and error patterns.
  </Accordion>

  <Accordion title="9. Stay up-to-date">
    Keep your integration current with the latest API changes:

    * Regularly check the [Changelog](/changelog) for updates.
    * Subscribe to the [Posta status page](https://status.posta.co) for notifications about API issues or downtime.
    * Update your error handling logic if new error types or codes are introduced.

    Set up a routine to review and update your integration to ensure it remains compatible with the latest API version.
  </Accordion>
</AccordionGroup>

By following these practices, you can create a robust error handling system that improves the reliability and user experience of your Posta API integration. Remember to test your error handling thoroughly, simulating various error scenarios to ensure your application behaves correctly in all situations.

## Testing error scenarios

When developing your integration, it's important to test various error scenarios to ensure your application handles them gracefully. Here are some strategies for simulating different errors:

1. **Authentication errors**: Use invalid or expired API keys to test 401 and 403 responses.
2. **Validation errors**: Send requests with missing or invalid parameters to trigger 400 responses.
3. **Rate limiting**: Exceed rate limits intentionally to test your backoff and retry logic.
4. **Server errors**: Use a mock server to simulate 5xx responses and test your retry mechanisms.

<Note>
  Always use a test environment or sandbox when simulating error scenarios to avoid impacting your production data or live mailings.
</Note>

## Getting help

If you encounter persistent errors or need help interpreting an error message, don't hesitate to reach out to our support team. When contacting support:

1. Provide the full request and error response, including all fields without your API Key.
2. Include relevant log entries or stack traces.
3. Describe the steps to reproduce the error.
4. Mention any recent changes to your integration that might be related to the issue.

<Info>
  Contact our [support team](mailto:support@posta.com) for assistance with API errors or integration issues.
</Info>

By understanding and properly handling these errors, you can create a robust integration with the Posta API that gracefully manages unexpected situations and provides a seamless experience for your users.
