# How do I capture and handle errors or exceptions when making requests to the Bedrock service in my code?

Source: https://zilliz.com/ai-faq/how-do-i-capture-and-handle-errors-or-exceptions-when-making-requests-to-the-bedrock-service-in-my-code
Author: zilliz

To capture and handle errors when making requests to AWS Bedrock, use structured exception handling in your code. AWS SDKs (like Boto3 for Python or the AWS SDK for JavaScript) provide specific exception classes for Bedrock service errors. Wrap your Bedrock API calls in `try/catch` blocks (or `try/except` in Python) to intercept errors. For example, in Python using Boto3:

```python
import boto3
from botocore.exceptions import ClientError

client = boto3.client('bedrock')
try:
 response = client.invoke_model(modelId='anthropic.claude-v2', body=request_body)
except ClientError as e:
 error_code = e.response['Error']['Code']
 error_message = e.response['Error']['Message']
 print(f"Error {error_code}: {error_message}")
```

The `ClientError` exception captures service-specific errors, and you can extract details like the error code and message from the response. Common Bedrock errors include `ValidationException` (invalid input), `AccessDeniedException` (permissions), and `ThrottlingException` (rate limiting).

---

Differentiate between retryable and non-retryable errors. Network issues (e.g., timeout errors) or 5xx server errors from Bedrock can often be retried, while 4xx client errors (except `ThrottlingException`) require fixing the request. Implement retries with exponential backoff to avoid overwhelming the service. For example:

```python
from botocore.config import Config

retry_config = Config(
 retries={
 'max_attempts': 3,
 'mode': 'standard' # Includes adaptive retry for throttling
 }
)
client = boto3.client('bedrock', config=retry_config)
```

This configuration tells the AWS SDK to automatically retry up to 3 times for retryable errors, with built-in backoff. For custom retry logic, use a library like `backoff` (Python) or implement a loop with increasing delays.

---

Validate requests before sending them to reduce preventable errors. Check input formats (e.g., prompt length limits for specific models) and permissions upfront. For example, validate that your IAM role has `bedrock:InvokeModel` permissions. Log errors with context (request ID, timestamp, model ID) using your framework’s logging tools, and monitor metrics like error rates via Amazon CloudWatch. Avoid silent failures by ensuring all exceptions are either handled or explicitly logged for debugging.
