Skip to content

Errors API Reference

This page documents all the custom exceptions that BWS SDK can raise.

Exception Hierarchy

BWS SDK defines several custom exceptions to help you handle different error conditions:

Exception
├── BWSSDKError (base class for all BWS SDK errors)
│   ├── ApiError
│   │   ├── SendRequestError
│   │   ├── SecretParseError
│   │   ├── UnauthorisedError
│   │   ├── SecretNotFoundError
│   │   └── APIRateLimitError
│   ├── AuthError
│   │   ├── InvalidTokenError
│   │   ├── UnauthorisedTokenError
│   │   ├── InvalidStateFileError
│   │   └── InvalidIdentityResponseError
│   └── CryptographyError
│       ├── HmacError
│       ├── InvalidEncryptedFormat
│       └── InvalidEncryptionKeyError

Base Exceptions

bws_sdk.errors.BWSSDKError

Bases: Exception

Base exception class for all BWS SDK related errors.

This is the root exception class for the BWS SDK. All other SDK-specific exceptions inherit from this class, allowing for broad exception handling when needed.

API Errors

bws_sdk.errors.ApiError

Bases: BWSSDKError

Base class for errors stemming from interaction with the BWS API.

This exception is raised for general API-related errors, including unexpected HTTP status codes and malformed API responses.

bws_sdk.errors.SendRequestError

Bases: ApiError

Raised when a network request to the BWS API fails.

This exception indicates that the HTTP request itself failed, typically due to network connectivity issues, DNS resolution failures, or connection timeouts.

bws_sdk.errors.SecretParseError

Bases: ApiError

Raised when a secret cannot be parsed or decrypted.

This exception occurs when the API returns secret data that cannot be properly parsed into a BitwardenSecret object or when decryption of the secret data fails.

bws_sdk.errors.UnauthorisedError

Bases: ApiError

Raised when the API returns a 401 Unauthorized response.

This exception indicates that the current authentication credentials are invalid or have expired.

bws_sdk.errors.SecretNotFoundError

Bases: ApiError

Raised when a requested secret is not found (404 response).

This exception occurs when attempting to retrieve a secret that doesn't exist or that the current user doesn't have permission to access.

bws_sdk.errors.APIRateLimitError

Bases: ApiError

Raised when the API rate limit is exceeded (429 response).

This exception indicates that too many requests have been made in a short time period and the client should wait before making additional requests.

Authentication Errors

bws_sdk.errors.AuthError

Bases: BWSSDKError

Base class for authentication-related errors.

This exception covers all authentication and authorization failures within the BWS SDK.

bws_sdk.errors.InvalidTokenError

Bases: AuthError

Raised when a BWS access token has an invalid format.

This exception occurs when parsing a BWS token string that doesn't conform to the expected format or contains invalid components.

bws_sdk.errors.UnauthorisedTokenError

Bases: AuthError

Raised when a BWS access token is rejected by the identity service.

This exception indicates that the token format is correct but the credentials are invalid or the token has been revoked.

bws_sdk.errors.InvalidStateFileError

Bases: AuthError

Raised when a state file has an invalid format or is corrupted.

This exception occurs when attempting to load authentication state from a file that doesn't contain the expected format or has been corrupted.

bws_sdk.errors.InvalidIdentityResponseError

Bases: AuthError

Raised when the identity service returns an invalid response.

This exception occurs when the BWS identity service response cannot be parsed or doesn't contain the expected fields for authentication.

Cryptography Errors

bws_sdk.errors.CryptographyError

Bases: BWSSDKError

Base class for cryptographic operation failures.

This exception covers all errors related to encryption, decryption, key derivation, and other cryptographic operations.

bws_sdk.errors.HmacError

Bases: CryptographyError

Raised when HMAC verification fails during decryption.

This exception indicates that the message authentication code verification failed, suggesting the data has been tampered with or the wrong decryption key was used.

bws_sdk.errors.InvalidEncryptedFormat

Bases: CryptographyError

Raised when encrypted data has an invalid format.

This exception occurs when encrypted data strings don't conform to the expected Bitwarden encrypted format or contain invalid base64 encoding.

bws_sdk.errors.InvalidEncryptionKeyError

Bases: CryptographyError

Raised when an encryption key has invalid length or format.

This exception occurs when attempting to use encryption keys that don't meet the required specifications for the cryptographic algorithms used by Bitwarden.

Error Handling Examples

Basic Error Handling

from bws_sdk import BWSecretClient, Region
from bws_sdk.errors import UnauthorisedError, SecretNotFoundError, APIRateLimitError

region = Region(
    api_url="https://api.bitwarden.com",
    identity_url="https://identity.bitwarden.com"
)

try:
    client = BWSecretClient(region, "your-access-token")
    secret = client.get_by_id("secret-id")
    print(f"Retrieved: {secret.key}")

except UnauthorisedError:
    print("Authentication failed - check your access token")
except SecretNotFoundError:
    print("Secret not found - check the secret ID")
except APIRateLimitError:
    print("Rate limit exceeded - wait before retrying")

Comprehensive Error Handling

from bws_sdk import BWSecretClient, Region
from bws_sdk.errors import (
    BWSSDKError, ApiError, CryptographyError,
    SendRequestError, InvalidTokenError
)

try:
    client = BWSecretClient(region, access_token)
    secret = client.get_by_id(secret_id)

except InvalidTokenError:
    print("Invalid token format")
except UnauthorisedError:
    print("Token expired or invalid")
except SecretNotFoundError:
    print("Secret does not exist")
except APIRateLimitError as e:
    print(f"Rate limited. Retry after: {e.retry_after} seconds")
except CryptographyError:
    print("Failed to decrypt secret")
except SendRequestError as e:
    print(f"Network error: {e}")
except ApiError as e:
    print(f"API error: {e.status_code} - {e}")
except BWSSDKError as e:
    print(f"BWS SDK error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Retry Logic with Rate Limiting

import time
from bws_sdk.errors import APIRateLimitError

def get_secret_with_retry(client, secret_id, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.get_by_id(secret_id)
        except APIRateLimitError as e:
            if attempt < max_retries - 1:
                sleep_time = getattr(e, 'retry_after', 60)
                print(f"Rate limited, waiting {sleep_time} seconds...")
                time.sleep(sleep_time)
            else:
                raise
        except Exception:
            # Don't retry on other errors
            raise