Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Appendix H: Error Code Reference

This appendix provides a comprehensive reference of all error codes, their HTTP status mappings, and recommended handling strategies.

Error Code Categories

Pierre uses four primary error enums:

  • ErrorCode - Application-level error codes with HTTP mapping
  • DatabaseError - Database operation errors
  • ProviderError - Fitness provider API errors
  • ProtocolError - Protocol operation errors (MCP/A2A)

ErrorCode → HTTP Status Mapping

Source: src/errors.rs:17-86

Authentication & Authorization (4xx)

Error CodeHTTP StatusDescriptionClient Action
AuthRequired401No authentication providedPrompt user to login
AuthInvalid401Invalid credentialsRe-authenticate
AuthExpired403Token has expiredRefresh token or re-login
AuthMalformed403Token is corruptedRe-authenticate
PermissionDenied403Insufficient permissionsRequest access or escalate

Rate Limiting (429)

Error CodeHTTP StatusDescriptionClient Action
RateLimitExceeded429Too many requestsImplement exponential backoff
QuotaExceeded429Monthly quota exceededUpgrade tier or wait for reset

Validation (400)

Error CodeHTTP StatusDescriptionClient Action
InvalidInput400Input validation failedFix input and retry
MissingRequiredField400Required field missingInclude required fields
InvalidFormat400Data format incorrectCheck API documentation
ValueOutOfRange400Value outside boundsUse valid value range

Resource Management (4xx)

Error CodeHTTP StatusDescriptionClient Action
ResourceNotFound404Resource doesn’t existCheck resource ID
ResourceAlreadyExists409Duplicate resourceUse existing or rename
ResourceLocked409Resource is lockedWait and retry
ResourceUnavailable503Temporarily unavailableRetry with backoff

External Services (5xx)

Error CodeHTTP StatusDescriptionClient Action
ExternalServiceError502Provider returned errorRetry or report issue
ExternalServiceUnavailable502Provider is downRetry later
ExternalAuthFailed503Provider auth failedRe-connect provider
ExternalRateLimited503Provider rate limitedWait for provider reset

Configuration (500)

Error CodeHTTP StatusDescriptionClient Action
ConfigError500Configuration errorContact administrator
ConfigMissing500Missing configurationContact administrator
ConfigInvalid500Invalid configurationContact administrator

Internal Errors (500)

Error CodeHTTP StatusDescriptionClient Action
InternalError500Unexpected server errorRetry, then report
DatabaseError500Database operation failedRetry, then report
StorageError500Storage operation failedRetry, then report
SerializationError500JSON parsing failedCheck request format

DatabaseError Variants

Source: src/database/errors.rs:10-140

VariantContext FieldsTypical Cause
NotFoundentity_type, entity_idQuery returned no rows
TenantIsolationViolationentity_type, entity_id, requested_tenant, actual_tenantCross-tenant access attempt
EncryptionFailedcontextEncryption key issue
DecryptionFailedcontextAAD mismatch or corrupt data
ConstraintViolationconstraint, detailsUnique/foreign key violation
ConnectionErrormessagePool exhausted or network
QueryErrorcontextSQL syntax or type error
MigrationErrorversion, detailsSchema migration failed
InvalidDatafield, reasonData type mismatch
PoolExhaustedmax_connections, wait_time_msToo many concurrent queries
TransactionRollbackreasonExplicit rollback
SchemaMismatchexpected, actualDatabase version mismatch
Timeoutoperation, timeout_secsQuery took too long
TransactionConflictdetailsDeadlock or serialization failure

ProviderError Variants

Source: src/providers/errors.rs:11-80

VariantContext FieldsRetry Strategy
ApiErrorprovider, status_code, message, retryableCheck retryable field
RateLimitExceededprovider, retry_after_secs, limit_typeWait retry_after_secs
AuthenticationFailedprovider, reasonRe-authenticate user
TokenExpiredproviderAuto-refresh token
InvalidResponseprovider, contextLog and skip activity
NetworkErrorprovider, messageRetry with backoff
Timeoutprovider, timeout_secsIncrease timeout or retry
NotSupportedprovider, featureFeature unavailable

ProtocolError Variants

Source: src/protocols/mod.rs:35-211

Protocol errors for MCP and A2A protocol operations:

Tool Errors

VariantContext FieldsTypical Cause
ToolNotFoundtool_id, available_countTool ID doesn’t exist
InvalidParametertool_id, parameter, reasonParameter validation failed
MissingParametertool_id, parameterRequired parameter not provided
InvalidParametersmessageGeneral parameter error
ExecutionFailedmessageTool execution error
ExecutionFailedDetailedtool_id, sourceTool execution with source error

Protocol Errors

VariantContext FieldsTypical Cause
UnsupportedProtocolprotocolProtocol type not supported
InvalidRequestmessageMalformed request
InvalidRequestDetailedprotocol, reasonRequest validation failure
ConversionFailedfrom, to, reasonProtocol format conversion error

Configuration Errors

VariantContext FieldsTypical Cause
ConfigMissingkeyRequired config not set
ConfigurationErrormessageGeneral config error
ConfigurationErrorDetailedmessageConfig error with details

Plugin Errors

VariantContext FieldsTypical Cause
PluginNotFoundplugin_idPlugin ID doesn’t exist
PluginErrorplugin_id, detailsPlugin execution failed

Access Control Errors

VariantContext FieldsTypical Cause
InsufficientSubscriptionrequired, currentUser tier too low
RateLimitExceededrequests, window_secsToo many requests

Other Errors

VariantContext FieldsTypical Cause
Serializationcontext, sourceJSON serialization failed
SerializationErrormessageSimple serialization error
DatabasesourceDatabase operation failed
InvalidSchemaentity, reasonSchema validation error
InternalErrormessageUnexpected server error
OperationCancelledmessageUser cancelled operation

JSON Error Response Format

All API errors return a consistent JSON structure:

{
  "error": {
    "code": "auth_expired",
    "message": "The authentication token has expired",
    "details": {
      "expired_at": "2025-01-15T10:30:00Z",
      "token_type": "access_token"
    },
    "request_id": "req_abc123"
  }
}

Fields:

  • code: Machine-readable error code (snake_case)
  • message: Human-readable description
  • details: Optional context-specific data
  • request_id: Correlation ID for debugging

MCP Error Response Format

For MCP protocol, errors follow JSON-RPC 2.0 spec:

{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": {
      "pierre_code": "invalid_input",
      "details": "Missing required field: provider"
    }
  }
}

JSON-RPC Error Codes:

CodeMeaningPierre Mapping
-32700Parse errorSerializationError
-32600Invalid RequestInvalidInput
-32601Method not foundResourceNotFound
-32602Invalid paramsInvalidInput
-32603Internal errorInternalError
-32000 to -32099Server errorApplication-specific

Retry Strategies

Exponential Backoff

#![allow(unused)]
fn main() {
// Standard retry with exponential backoff
let delays = [100, 200, 400, 800, 1600]; // milliseconds

for (attempt, delay) in delays.iter().enumerate() {
    match operation().await {
        Ok(result) => return Ok(result),
        Err(e) if e.is_retryable() => {
            tokio::time::sleep(Duration::from_millis(*delay)).await;
        }
        Err(e) => return Err(e),
    }
}
}

Rate Limit Handling

#![allow(unused)]
fn main() {
match provider.get_activities().await {
    Err(ProviderError::RateLimitExceeded { retry_after_secs, .. }) => {
        // Respect Retry-After header
        tokio::time::sleep(Duration::from_secs(retry_after_secs)).await;
        provider.get_activities().await
    }
    result => result,
}
}

Error Logging

All errors are logged with structured context:

#![allow(unused)]
fn main() {
tracing::error!(
    error_code = %error.code(),
    http_status = error.http_status(),
    request_id = %request_id,
    user_id = %user_id,
    "Operation failed: {}", error
);
}

Key Takeaways

  1. Consistent HTTP mapping: ErrorCode::http_status() provides standardized status codes.
  2. Structured context: All errors include relevant context fields for debugging.
  3. Retry guidance: retryable field and retry_after_secs guide client behavior.
  4. Tenant isolation: TenantIsolationViolation is a security-critical error.
  5. JSON-RPC compliance: MCP errors follow JSON-RPC 2.0 specification.
  6. Request correlation: All errors include request_id for distributed tracing.

Related Chapters:

  • Chapter 2: Error Handling (structured error patterns)
  • Chapter 9: JSON-RPC Foundation (MCP error codes)
  • Appendix E: Rate Limiting (quota errors)