🔍 Code Extractor

class ApiError

Maturity: 38

A custom exception class for API-related errors, specifically designed to handle cases where a requested document cannot be found.

File:
/tf/active/vicechatdev/rmcl/exceptions.py
Lines:
28 - 32
Complexity:
simple

Purpose

ApiError is a custom exception class that extends Python's built-in Exception class. It is designed to be raised when API operations fail, particularly when a requested document cannot be found. The class stores both an error message and an optional response object, allowing developers to access the full API response context when handling the exception. This is useful for debugging and providing detailed error information to users or logging systems.

Source Code

class ApiError(Exception):
    """Could not found a requested document"""
    def __init__(self, msg, response=None):
        self.response = response
        super(ApiError, self).__init__(msg)

Parameters

Name Type Default Kind
bases Exception -

Parameter Details

msg: A string message describing the error that occurred. This message will be passed to the parent Exception class and can be accessed via str(exception) or exception.args[0]. It should provide clear information about what went wrong.

response: An optional parameter that stores the API response object associated with the error. This can be any type (typically a requests.Response object or similar), allowing access to status codes, headers, and response body for debugging purposes. Defaults to None if not provided.

Return Value

Instantiating ApiError returns an exception object that can be raised. The object contains the error message (accessible via standard exception mechanisms) and a 'response' attribute that stores the optional response object. When raised and caught, the exception can be examined to retrieve both the message and the response details.

Class Interface

Methods

__init__(self, msg, response=None)

Purpose: Initializes the ApiError exception with an error message and optional response object

Parameters:

  • msg: String message describing the error
  • response: Optional API response object (defaults to None)

Returns: None (constructor)

Attributes

Name Type Description Scope
response Any (typically requests.Response or similar, can be None) Stores the API response object associated with the error, allowing access to status codes, headers, and response body for debugging. May be None if no response was provided. instance

Usage Example

# Basic usage - raising the exception
try:
    # Simulating an API call that fails
    raise ApiError("Document with ID 12345 not found")
except ApiError as e:
    print(f"Error occurred: {e}")
    print(f"Response object: {e.response}")

# Usage with response object
import requests

try:
    response = requests.get("https://api.example.com/document/12345")
    if response.status_code == 404:
        raise ApiError("Document not found", response=response)
except ApiError as e:
    print(f"Error: {e}")
    if e.response:
        print(f"Status code: {e.response.status_code}")
        print(f"Response body: {e.response.text}")

# Catching in exception hierarchy
try:
    raise ApiError("Something went wrong")
except Exception as e:
    # ApiError is caught as it inherits from Exception
    print(f"Caught exception: {type(e).__name__}")

Best Practices

  • Always provide a descriptive error message when raising ApiError to help with debugging and error tracking.
  • Include the response object when available to preserve full context of the API failure for debugging purposes.
  • Catch ApiError specifically when you need to handle API-related errors differently from other exceptions.
  • Consider logging both the message and response details when catching this exception for better observability.
  • The docstring mentions 'Could not found a requested document' but the class can be used for any API error - consider the docstring as a primary use case rather than a limitation.
  • Since ApiError inherits from Exception, it can be caught by generic exception handlers, so place specific ApiError handlers before generic Exception handlers.
  • The response attribute is optional and may be None, so always check for its existence before accessing its properties.
  • This exception is typically raised by API client code and caught by calling code that needs to handle API failures gracefully.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class DocumentNotFound 68.8% similar

    A custom exception class that is raised when a requested document cannot be found in the system.

    From: /tf/active/vicechatdev/rmcl/exceptions.py
  • class DocumentProcessingError 64.0% similar

    Custom exception class for handling errors that occur during document processing operations.

    From: /tf/active/vicechatdev/CDocs/utils/document_processor.py
  • class AuthError 62.7% similar

    A custom exception class for handling authentication-related errors in an application.

    From: /tf/active/vicechatdev/rmcl/exceptions.py
  • class PermissionError 61.5% similar

    Custom exception class that signals when a user attempts an action they lack permission to perform.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • class ResourceNotFoundError_v1 61.3% similar

    A custom exception class that is raised when a requested resource cannot be found in the system.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
← Back to Browse