Errors

Handling Errors in the API

The API provides a structured way to report errors, helping you understand what went wrong and how to resolve the issue. Errors are categorized by their type and are returned in a clear, consistent JSON format. Below is an overview of common error types and how to handle them, along with an example of the error response structure.

Error Response Structure

For most errors, the API returns a response in the following format:

{
  "type": "client_error",  // Type of error (e.g., client_error or server_error)
  "errors": [
    {
      "code": "error_code",   // A unique code identifying the error
      "detail": "Detailed explanation of the error.",  // A message explaining the error
      "attr": "field_name",   // (optional) The specific field related to the error
      "extra": "additional_info"  // (optional) Any extra details relevant to the error
    }
  ]
}

Here’s a breakdown of each field:

  • type: Describes the category of the error. This can be client_error (issues with the request) or server_error (issues on the server).

  • errors: A list of one or more errors.

    • code: A unique error code that helps identify the specific issue.

    • detail: A detailed message explaining the error.

    • attr: (Optional) If the error is related to a specific field (e.g., missing or invalid data), this indicates the field name.

    • extra: (Optional) Additional information that might help you troubleshoot the issue.


Common Error Types

1. Validation Errors

Validation errors occur when the data in your request doesn’t meet the expected format, type, or rules defined by the API. These are considered client-side errors (4xx) and typically return a 400 Bad Request response. The API will provide a detailed error response structure to help you identify which field(s) failed validation and why.

Validation Error Response Structure

When a validation error occurs, the API returns a JSON response like this:

{
  "type": "validation_error",
  "errors": [
    {
      "code": "invalid_field_value",
      "detail": "The 'email' field must be a valid email address.",
      "attr": "email",
      "extra": null
    },
    {
      "code": "required_field",
      "detail": "The 'password' field is required.",
      "attr": "password",
      "extra": null
    }
  ]
}

Fields in a Validation Error Response:

  • type: This will be set to validation_error to indicate that the error occurred due to invalid input or missing fields.

  • errors: An array of one or more errors encountered during validation.

    • code: A unique identifier for the type of validation error (e.g., invalid_field_value, required_field).

    • detail: A message explaining the error in detail, including why the validation failed.

    • attr: The name of the field that caused the validation error (e.g., email, password).

    • extra: (Optional) Any additional information to provide more context about the validation error. This might include hints on valid values or other requirements.

Common Validation Errors:

Here are some typical validation errors you may encounter:

  • Invalid Field Value:

    • The value provided for a field does not meet the expected format or type.

    • Example: Entering an invalid email address.

    {
      "code": "invalid_field_value",
      "detail": "The 'email' field must be a valid email address.",
      "attr": "email",
      "extra": null
    }
  • Required Field:

    • A required field was not provided in the request.

    • Example: Omitting the password field in a registration request.

    {
      "code": "required_field",
      "detail": "The 'password' field is required.",
      "attr": "password",
      "extra": null
    }
  • Field Too Short/Long:

    • The value provided for a field does not meet the minimum or maximum length requirement.

    • Example: A password is too short.

    {
      "code": "field_too_short",
      "detail": "The 'password' field must be at least 8 characters long.",
      "attr": "password",
      "extra": null
    }
  • Invalid Choice:

    • A field contains a value that is not one of the accepted choices.

    • Example: Passing an invalid value for a status field.

    {
      "code": "invalid_choice",
      "detail": "The value 'pending' is not a valid choice for 'status'.",
      "attr": "status",
      "extra": ["active", "inactive", "suspended"]
    }

Example of Validation Error Response:

If you submit a request to create a new user but forget to include required fields like email and password, you might receive a response like this:

{
  "type": "validation_error",
  "errors": [
    {
      "code": "required_field",
      "detail": "The 'email' field is required.",
      "attr": "email",
      "extra": null
    },
    {
      "code": "required_field",
      "detail": "The 'password' field is required.",
      "attr": "password",
      "extra": null
    }
  ]
}

Best Practices for Handling Validation Errors:

  1. Check for Validation Errors First: Always validate the input data before sending a request to the API. This helps prevent unnecessary errors and reduces the load on both your application and the API.

  2. Examine the attr Field: The attr field tells you which field in your request caused the validation error. Use this information to provide clear feedback to the user.

  3. User-Friendly Error Messages: Use the detail field to display user-friendly error messages. These can guide users to correct the input in your application's UI.

  4. Handle extra Information: In some cases, the extra field will provide more details about valid values or constraints. Use this information to validate input and provide meaningful hints to users.

Summary:

Validation errors are client-side issues that occur when your request data doesn't meet the expected format or rules. The API will return a structured JSON response with helpful details about which fields caused the error and why. By handling these errors correctly and validating input before sending requests, you can create a smoother experience for users and avoid unnecessary API errors.

2. Client Errors (4xx)

These errors occur when there is something wrong with the request you’re making.

  • 401 Unauthorized:

    • The request lacks valid authentication credentials. This could be due to a missing or invalid token.

    {
      "type": "client_error",
      "errors": [
        {
          "code": "invalid_token",
          "detail": "The provided token is expired or invalid.",
          "attr": null,
          "extra": null
        }
      ]
    }
  • 403 Forbidden:

    • The request is valid, but you don’t have permission to perform the action.

    {
      "type": "client_error",
      "errors": [
        {
          "code": "forbidden",
          "detail": "You do not have permission to delete this dataset.",
          "attr": null,
          "extra": null
        }
      ]
    }
  • 404 Not Found:

    • The requested resource could not be found. This may occur if the URL is incorrect or the resource doesn’t exist.

    {
      "type": "client_error",
      "errors": [
        {
          "code": "not_found",
          "detail": "The requested dataset was not found.",
          "attr": null,
          "extra": null
        }
      ]
    }
  • 429 Too Many Requests:

    • You have exceeded the rate limit or made too many attempts in a short period. For example, repeated failed login attempts.

    {
      "type": "client_error",
      "errors": [
        {
          "code": "too_many_attempts_try_later",
          "detail": "Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or try again later.",
          "attr": null,
          "extra": null
        }
      ]
    }

3. Server Errors (5xx)

These errors occur when something goes wrong on the server side.

  • 500 Internal Server Error:

    • A generic error indicating something went wrong on the server. The error message may not always be detailed, but it signals an issue with the server's ability to process the request.

    {
      "type": "server_error",
      "errors": [
        {
          "code": "internal_server_error",
          "detail": "An unexpected error occurred on the server. Please try again later.",
          "attr": null,
          "extra": null
        }
      ]
    }
  • 502 Bad Gateway:

    • This error indicates that the API server is acting as a gateway or proxy and received an invalid response from the upstream server. Since this is a server-side issue, the response may not be in JSON format.

    HTTP/1.1 502 Bad Gateway
  • 503 Service Unavailable:

    • The server is temporarily unable to handle the request, often due to overload or maintenance. Like the 502 error, this response is not returned in JSON format.

    HTTP/1.1 503 Service Unavailable

Best Practices for Handling Errors:

  1. Check the type and code: Always inspect the type field to identify if it’s a client or server error, and use the code to understand the specific issue.

  2. Read the detail Field: The detail field will usually provide a clear explanation of the error, which can guide you toward a solution.

  3. Retry for 5xx Errors: For server-side errors (5xx), consider implementing a retry strategy with exponential backoff to handle temporary server issues.

  4. Rate Limit Handling: If you encounter a 429 Too Many Requests error, ensure your application handles this gracefully, possibly by implementing delays between requests or retrying after a certain period.

Last updated