Module astrapy.exceptions

Sub-modules

astrapy.exceptions.collection_exceptions
astrapy.exceptions.data_api_exceptions
astrapy.exceptions.devops_api_exceptions
astrapy.exceptions.error_descriptors
astrapy.exceptions.table_exceptions
astrapy.exceptions.utils

Classes

class CollectionDeleteManyException (partial_result: CollectionDeleteResult, cause: Exception)
Expand source code
@dataclass
class CollectionDeleteManyException(DataAPIException):
    """
    An exception occurring during a delete_many (an operation that can span
    several requests). As such, besides information on the root-cause error,
    there may be a partial result about the part that succeeded.

    Attributes:
        partial_result: a CollectionDeleteResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
        cause: a root exception that happened during the delete_many, causing
            the method call to stop and raise this error.
    """

    partial_result: CollectionDeleteResult
    cause: Exception

    def __str__(self) -> str:
        return f"{self.__class__.__name__}({self.cause.__str__()})"

An exception occurring during a delete_many (an operation that can span several requests). As such, besides information on the root-cause error, there may be a partial result about the part that succeeded.

Attributes

partial_result
a CollectionDeleteResult object, just like the one that would be the return value of the operation, had it succeeded completely.
cause
a root exception that happened during the delete_many, causing the method call to stop and raise this error.

Ancestors

Instance variables

var cause : Exception

The type of the None singleton.

var partial_result : CollectionDeleteResult

The type of the None singleton.

class CollectionInsertManyException (inserted_ids: list[Any], exceptions: Sequence[Exception])
Expand source code
@dataclass
class CollectionInsertManyException(DataAPIException):
    """
    An exception occurring within an insert_many (an operation that can span
    several requests). As such, it represents both the root error(s) that happened
    and information on the portion of the documents that were successfully inserted.

    The behaviour of insert_many (concurrency and the `ordered` setting) make it
    possible that more than one "root errors" are collected.

    Attributes:
        inserted_ids: a list of the document IDs that have been successfully inserted.
        exceptions: a list of the root exceptions leading to this error. The list,
            under normal circumstances, is not empty.
    """

    inserted_ids: list[Any]
    exceptions: Sequence[Exception]

    def __str__(self) -> str:
        num_ids = len(self.inserted_ids)
        if self.exceptions:
            exc_desc: str
            excs_strs = [exc.__str__() for exc in self.exceptions[:8]]
            if len(self.exceptions) > 8:
                exc_desc = ", ".join(excs_strs) + " ... (more exceptions)"
            else:
                exc_desc = ", ".join(excs_strs)
            return (
                f"{self.__class__.__name__}({exc_desc} [with {num_ids} inserted ids])"
            )
        else:
            return f"{self.__class__.__name__}()"

An exception occurring within an insert_many (an operation that can span several requests). As such, it represents both the root error(s) that happened and information on the portion of the documents that were successfully inserted.

The behaviour of insert_many (concurrency and the ordered setting) make it possible that more than one "root errors" are collected.

Attributes

inserted_ids
a list of the document IDs that have been successfully inserted.
exceptions
a list of the root exceptions leading to this error. The list, under normal circumstances, is not empty.

Ancestors

Instance variables

var exceptions : Sequence[Exception]

The type of the None singleton.

var inserted_ids : list[typing.Any]

The type of the None singleton.

class CollectionUpdateManyException (partial_result: CollectionUpdateResult, cause: Exception)
Expand source code
@dataclass
class CollectionUpdateManyException(DataAPIException):
    """
    An exception occurring during an update_many (an operation that can span
    several requests). As such, besides information on the root-cause error,
    there may be a partial result about the part that succeeded.

    Attributes:
        partial_result: a CollectionUpdateResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
        cause: a root exception that happened during the update_many, causing
            the method call to stop and raise this error.
    """

    partial_result: CollectionUpdateResult
    cause: Exception

    def __str__(self) -> str:
        return f"{self.__class__.__name__}({self.cause.__str__()})"

An exception occurring during an update_many (an operation that can span several requests). As such, besides information on the root-cause error, there may be a partial result about the part that succeeded.

Attributes

partial_result
a CollectionUpdateResult object, just like the one that would be the return value of the operation, had it succeeded completely.
cause
a root exception that happened during the update_many, causing the method call to stop and raise this error.

Ancestors

Instance variables

var cause : Exception

The type of the None singleton.

var partial_result : CollectionUpdateResult

The type of the None singleton.

class CursorException (text: str, *, cursor_state: str)
Expand source code
@dataclass
class CursorException(DataAPIException):
    """
    The cursor operation cannot be invoked if a cursor is not in its pristine
    state (i.e. is already being consumed or is exhausted altogether).

    Attributes:
        text: a text message about the exception.
        cursor_state: a string description of the current state
            of the cursor. See the documentation for Cursor.
    """

    text: str
    cursor_state: str

    def __init__(
        self,
        text: str,
        *,
        cursor_state: str,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.cursor_state = cursor_state

The cursor operation cannot be invoked if a cursor is not in its pristine state (i.e. is already being consumed or is exhausted altogether).

Attributes

text
a text message about the exception.
cursor_state
a string description of the current state of the cursor. See the documentation for Cursor.

Ancestors

Instance variables

var cursor_state : str

The type of the None singleton.

var text : str

The type of the None singleton.

class DataAPIErrorDescriptor (error_dict: dict[str, str] | str)
Expand source code
@dataclass
class DataAPIErrorDescriptor:
    """
    An object representing a single error, as returned from the Data API,
    typically with an error code, a text message and other properties.

    This object is used to describe errors received from the Data API,
    in the form of HTTP-200 ("success") responses containing errors

    Depending on the API command semantics, responses may express partial
    successes with some errors (for instance, an insertMany command inserting
    most of the documents/rows, but failing on a couple of incompatible inputs).

    Attributes:
        error_code: a string code as found in the API error's "errorCode" field.
        message: the text found in the API error's "message" field.
        title:  the text found in the API error's "title" field.
        family:  the text found in the API error's "family" field.
        scope:  the text found in the API error's "scope" field.
        id:  the text found in the API error's "id" field.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    title: str | None
    error_code: str | None
    message: str | None
    family: str | None
    scope: str | None
    id: str | None
    attributes: dict[str, Any]

    _known_dict_fields = {
        "title",
        "errorCode",
        "message",
        "family",
        "scope",
        "id",
    }

    def __init__(self, error_dict: dict[str, str] | str) -> None:
        if isinstance(error_dict, str):
            self.message = error_dict
            self.title = None
            self.error_code = None
            self.family = None
            self.scope = None
            self.id = None
            self.attributes = {}
        else:
            self.title = error_dict.get("title")
            self.error_code = error_dict.get("errorCode")
            self.message = error_dict.get("message")
            self.family = error_dict.get("family")
            self.scope = error_dict.get("scope")
            self.id = error_dict.get("id")
            self.attributes = {
                k: v for k, v in error_dict.items() if k not in self._known_dict_fields
            }

    def __repr__(self) -> str:
        pieces = [
            f"{self.title.__repr__()}" if self.title else None,
            f"error_code={self.error_code.__repr__()}" if self.error_code else None,
            f"message={self.message.__repr__()}" if self.message else None,
            f"family={self.family.__repr__()}" if self.family else None,
            f"scope={self.scope.__repr__()}" if self.scope else None,
            f"id={self.id.__repr__()}" if self.id else None,
            f"attributes={self.attributes.__repr__()}" if self.attributes else None,
        ]
        return f"{self.__class__.__name__}({', '.join(pc for pc in pieces if pc)})"

    def __str__(self) -> str:
        return self.summary()

    def summary(self) -> str:
        """
        Determine a string succinct description of this descriptor.

        The precise format of this summary is determined by which fields are set.
        """
        non_code_part: str | None
        if self.title:
            if self.message:
                non_code_part = f"{self.title}: {self.message}"
            else:
                non_code_part = f"{self.title}"
        else:
            if self.message:
                non_code_part = f"{self.message}"
            else:
                non_code_part = None
        if self.error_code:
            if non_code_part:
                return f"{non_code_part} ({self.error_code})"
            else:
                return f"{self.error_code}"
        else:
            if non_code_part:
                return non_code_part
            else:
                return ""

An object representing a single error, as returned from the Data API, typically with an error code, a text message and other properties.

This object is used to describe errors received from the Data API, in the form of HTTP-200 ("success") responses containing errors

Depending on the API command semantics, responses may express partial successes with some errors (for instance, an insertMany command inserting most of the documents/rows, but failing on a couple of incompatible inputs).

Attributes

error_code
a string code as found in the API error's "errorCode" field.
message
the text found in the API error's "message" field.
title
the text found in the API error's "title" field.
family
the text found in the API error's "family" field.
scope
the text found in the API error's "scope" field.
id
the text found in the API error's "id" field.
attributes
a dict with any further key-value pairs returned by the API.

Subclasses

Instance variables

var attributes : dict[str, typing.Any]

The type of the None singleton.

var error_code : str | None

The type of the None singleton.

var family : str | None

The type of the None singleton.

var id : str | None

The type of the None singleton.

var message : str | None

The type of the None singleton.

var scope : str | None

The type of the None singleton.

var title : str | None

The type of the None singleton.

Methods

def summary(self) ‑> str
Expand source code
def summary(self) -> str:
    """
    Determine a string succinct description of this descriptor.

    The precise format of this summary is determined by which fields are set.
    """
    non_code_part: str | None
    if self.title:
        if self.message:
            non_code_part = f"{self.title}: {self.message}"
        else:
            non_code_part = f"{self.title}"
    else:
        if self.message:
            non_code_part = f"{self.message}"
        else:
            non_code_part = None
    if self.error_code:
        if non_code_part:
            return f"{non_code_part} ({self.error_code})"
        else:
            return f"{self.error_code}"
    else:
        if non_code_part:
            return non_code_part
        else:
            return ""

Determine a string succinct description of this descriptor.

The precise format of this summary is determined by which fields are set.

class DataAPIException (*args, **kwargs)
Expand source code
class DataAPIException(Exception):
    """
    Any exception occurred while issuing requests to the Data API
    and specific to it, such as:
      - a collection is found not to exist when gettings its metadata,
      - the API return a response with an error,
    but not, for instance,
      - a network error while sending an HTTP request to the API.
    """

    pass

Any exception occurred while issuing requests to the Data API and specific to it, such as: - a collection is found not to exist when gettings its metadata, - the API return a response with an error, but not, for instance, - a network error while sending an HTTP request to the API.

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class DataAPIHttpException (text: str | None,
*,
httpx_error: httpx.HTTPStatusError,
error_descriptors: list[DataAPIErrorDescriptor])
Expand source code
@dataclass
class DataAPIHttpException(DataAPIException, httpx.HTTPStatusError):
    """
    A request to the Data API resulted in an HTTP 4xx or 5xx response.

    In most cases this comes with additional information: the purpose
    of this class is to present such information in a structured way,
    akin to what happens for the DataAPIResponseException, while
    still raising (a subclass of) `httpx.HTTPStatusError`.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found in the response.
    """

    text: str | None
    error_descriptors: list[DataAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        httpx_error: httpx.HTTPStatusError,
        error_descriptors: list[DataAPIErrorDescriptor],
    ) -> None:
        DataAPIException.__init__(self, text)
        httpx.HTTPStatusError.__init__(
            self,
            message=str(httpx_error),
            request=httpx_error.request,
            response=httpx_error.response,
        )
        self.text = text
        self.httpx_error = httpx_error
        self.error_descriptors = error_descriptors

    def __str__(self) -> str:
        return self.text or str(self.httpx_error)

    @classmethod
    def from_httpx_error(
        cls,
        httpx_error: httpx.HTTPStatusError,
        **kwargs: Any,
    ) -> DataAPIHttpException:
        """Parse a httpx status error into this exception."""

        raw_response: dict[str, Any]
        # the attempt to extract a response structure cannot afford failure.
        try:
            raw_response = httpx_error.response.json() or {}
        except Exception:
            raw_response = {}
        error_descriptors = [
            DataAPIErrorDescriptor(error_dict)
            for error_dict in raw_response.get("errors") or []
        ]
        if error_descriptors:
            text = f"{error_descriptors[0].message}. {str(httpx_error)}"
        else:
            text = str(httpx_error)

        return cls(
            text=text,
            httpx_error=httpx_error,
            error_descriptors=error_descriptors,
            **kwargs,
        )

A request to the Data API resulted in an HTTP 4xx or 5xx response.

In most cases this comes with additional information: the purpose of this class is to present such information in a structured way, akin to what happens for the DataAPIResponseException, while still raising (a subclass of) httpx.HTTPStatusError.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found in the response.

Ancestors

  • DataAPIException
  • httpx.HTTPStatusError
  • httpx.HTTPError
  • builtins.Exception
  • builtins.BaseException

Static methods

def from_httpx_error(httpx_error: httpx.HTTPStatusError, **kwargs: Any) ‑> DataAPIHttpException

Parse a httpx status error into this exception.

Instance variables

var error_descriptors : list[DataAPIErrorDescriptor]

The type of the None singleton.

var text : str | None

The type of the None singleton.

class DataAPIResponseException (text: str | None,
*,
command: dict[str, Any] | None,
raw_response: dict[str, Any],
error_descriptors: list[DataAPIErrorDescriptor],
warning_descriptors: list[DataAPIWarningDescriptor])
Expand source code
@dataclass
class DataAPIResponseException(DataAPIException):
    """
    The Data API returned an HTTP 200 ("success") response, which however
    reports API-specific error(s), possibly alongside partial successes.

    Attributes:
        text: a text message about the exception.
        command: the payload to the API that led to the response.
        raw_response: the full response from the API.
        error_descriptors: a list of DataAPIErrorDescriptor, one for each
            item in the API response's "errors" field.
        warning_descriptors: a list of DataAPIWarningDescriptor, one for each
            item in the API response's "warnings" field (if there are any).
    """

    text: str | None
    command: dict[str, Any] | None
    raw_response: dict[str, Any]
    error_descriptors: list[DataAPIErrorDescriptor]
    warning_descriptors: list[DataAPIWarningDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
        error_descriptors: list[DataAPIErrorDescriptor],
        warning_descriptors: list[DataAPIWarningDescriptor],
    ) -> None:
        super().__init__(text)
        self.text = text
        self.command = command
        self.raw_response = raw_response
        self.error_descriptors = error_descriptors
        self.warning_descriptors = warning_descriptors

    @staticmethod
    def from_response(
        *,
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
        **kwargs: Any,
    ) -> DataAPIResponseException:
        """Parse a raw response from the API into this exception."""

        error_descriptors = [
            DataAPIErrorDescriptor(error_dict)
            for error_dict in (raw_response or {}).get("errors") or []
        ]
        warning_descriptors = [
            DataAPIWarningDescriptor(error_dict)
            for error_dict in (raw_response or {}).get("warnings") or []
        ]

        if error_descriptors:
            summaries = [e_d.summary() for e_d in error_descriptors]
            if len(summaries) == 1:
                text = summaries[0]
            else:
                _j_summaries = "; ".join(
                    f"[{summ_i + 1}] {summ_s}"
                    for summ_i, summ_s in enumerate(summaries)
                )
                text = f"[{len(summaries)} errors collected] {_j_summaries}"
        else:
            text = ""

        return DataAPIResponseException(
            text,
            command=command,
            raw_response=raw_response,
            error_descriptors=error_descriptors,
            warning_descriptors=warning_descriptors,
            **kwargs,
        )

The Data API returned an HTTP 200 ("success") response, which however reports API-specific error(s), possibly alongside partial successes.

Attributes

text
a text message about the exception.
command
the payload to the API that led to the response.
raw_response
the full response from the API.
error_descriptors
a list of DataAPIErrorDescriptor, one for each item in the API response's "errors" field.
warning_descriptors
a list of DataAPIWarningDescriptor, one for each item in the API response's "warnings" field (if there are any).

Ancestors

Static methods

def from_response(*, command: dict[str, Any] | None, raw_response: dict[str, Any], **kwargs: Any) ‑> DataAPIResponseException
Expand source code
@staticmethod
def from_response(
    *,
    command: dict[str, Any] | None,
    raw_response: dict[str, Any],
    **kwargs: Any,
) -> DataAPIResponseException:
    """Parse a raw response from the API into this exception."""

    error_descriptors = [
        DataAPIErrorDescriptor(error_dict)
        for error_dict in (raw_response or {}).get("errors") or []
    ]
    warning_descriptors = [
        DataAPIWarningDescriptor(error_dict)
        for error_dict in (raw_response or {}).get("warnings") or []
    ]

    if error_descriptors:
        summaries = [e_d.summary() for e_d in error_descriptors]
        if len(summaries) == 1:
            text = summaries[0]
        else:
            _j_summaries = "; ".join(
                f"[{summ_i + 1}] {summ_s}"
                for summ_i, summ_s in enumerate(summaries)
            )
            text = f"[{len(summaries)} errors collected] {_j_summaries}"
    else:
        text = ""

    return DataAPIResponseException(
        text,
        command=command,
        raw_response=raw_response,
        error_descriptors=error_descriptors,
        warning_descriptors=warning_descriptors,
        **kwargs,
    )

Parse a raw response from the API into this exception.

Instance variables

var command : dict[str, typing.Any] | None

The type of the None singleton.

var error_descriptors : list[DataAPIErrorDescriptor]

The type of the None singleton.

var raw_response : dict[str, typing.Any]

The type of the None singleton.

var text : str | None

The type of the None singleton.

var warning_descriptors : list[DataAPIWarningDescriptor]

The type of the None singleton.

class DataAPITimeoutException (text: str, *, timeout_type: str, endpoint: str | None, raw_payload: str | None)
Expand source code
@dataclass
class DataAPITimeoutException(DataAPIException):
    """
    A Data API operation timed out. This can be a request timeout occurring
    during a specific HTTP request, or can happen over the course of a method
    involving several requests in a row, such as a paginated find.

    Attributes:
        text: a textual description of the error
        timeout_type: this denotes the phase of the HTTP request when the event
            occurred ("connect", "read", "write", "pool") or "generic" if there is
            not a specific request associated to the exception.
        endpoint: if the timeout is tied to a specific request, this is the
            URL that the request was targeting.
        raw_payload:  if the timeout is tied to a specific request, this is the
            associated payload (as a string).
    """

    text: str
    timeout_type: str
    endpoint: str | None
    raw_payload: str | None

    def __init__(
        self,
        text: str,
        *,
        timeout_type: str,
        endpoint: str | None,
        raw_payload: str | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.timeout_type = timeout_type
        self.endpoint = endpoint
        self.raw_payload = raw_payload

A Data API operation timed out. This can be a request timeout occurring during a specific HTTP request, or can happen over the course of a method involving several requests in a row, such as a paginated find.

Attributes

text
a textual description of the error
timeout_type
this denotes the phase of the HTTP request when the event occurred ("connect", "read", "write", "pool") or "generic" if there is not a specific request associated to the exception.
endpoint
if the timeout is tied to a specific request, this is the URL that the request was targeting.
raw_payload
if the timeout is tied to a specific request, this is the associated payload (as a string).

Ancestors

Instance variables

var endpoint : str | None

The type of the None singleton.

var raw_payload : str | None

The type of the None singleton.

var text : str

The type of the None singleton.

var timeout_type : str

The type of the None singleton.

class DataAPIWarningDescriptor (error_dict: dict[str, str] | str)
Expand source code
@dataclass
class DataAPIWarningDescriptor(DataAPIErrorDescriptor):
    """
    An object representing a single warning, as returned from the Data API,
    typically with a code, a text message and other properties.

    This object is used to describe warnings received from the Data API,
    in the form of HTTP-200 ("success") responses with accompanying warnings.

    Attributes:
        error_code: a string code found in the API warning's "errorCode" field.
        message: the text found in the API warning's "message" field.
        title:  the text found in the API warning's "title" field.
        family:  the text found in the API warning's "family" field.
        scope:  the text found in the API warning's "scope" field.
        id:  the text found in the API warning's "id" field.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    def __init__(self, error_dict: dict[str, str] | str) -> None:
        return DataAPIErrorDescriptor.__init__(self, error_dict=error_dict)

An object representing a single warning, as returned from the Data API, typically with a code, a text message and other properties.

This object is used to describe warnings received from the Data API, in the form of HTTP-200 ("success") responses with accompanying warnings.

Attributes

error_code
a string code found in the API warning's "errorCode" field.
message
the text found in the API warning's "message" field.
title
the text found in the API warning's "title" field.
family
the text found in the API warning's "family" field.
scope
the text found in the API warning's "scope" field.
id
the text found in the API warning's "id" field.
attributes
a dict with any further key-value pairs returned by the API.

Ancestors

Inherited members

class DevOpsAPIErrorDescriptor (error_dict: dict[str, Any])
Expand source code
@dataclass
class DevOpsAPIErrorDescriptor:
    """
    An object representing a single error returned from the DevOps API,
    typically with an error code and a text message.

    A single response from the Devops API may return zero, one or more of these.

    Attributes:
        id: a numeric code as found in the API "ID" item.
        message: the text found in the API "error" item.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    id: int | None
    message: str | None
    attributes: dict[str, Any]

    def __init__(self, error_dict: dict[str, Any]) -> None:
        self.id = error_dict.get("ID")
        self.message = error_dict.get("message")
        self.attributes = {
            k: v for k, v in error_dict.items() if k not in {"ID", "message"}
        }

An object representing a single error returned from the DevOps API, typically with an error code and a text message.

A single response from the Devops API may return zero, one or more of these.

Attributes

id
a numeric code as found in the API "ID" item.
message
the text found in the API "error" item.
attributes
a dict with any further key-value pairs returned by the API.

Instance variables

var attributes : dict[str, typing.Any]

The type of the None singleton.

var id : int | None

The type of the None singleton.

var message : str | None

The type of the None singleton.

class DevOpsAPIException (text: str | None = None)
Expand source code
class DevOpsAPIException(Exception):
    """
    An exception specific to issuing requests to the DevOps API.
    """

    def __init__(self, text: str | None = None):
        Exception.__init__(self, text or "")

An exception specific to issuing requests to the DevOps API.

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class DevOpsAPIHttpException (text: str | None,
*,
httpx_error: httpx.HTTPStatusError,
error_descriptors: list[DevOpsAPIErrorDescriptor])
Expand source code
@dataclass
class DevOpsAPIHttpException(DevOpsAPIException, httpx.HTTPStatusError):
    """
    A request to the DevOps API resulted in an HTTP 4xx or 5xx response.

    Though the DevOps API seldom enriches such errors with a response text,
    this class acts as the DevOps counterpart to DataAPIHttpException
    to facilitate a symmetryc handling of errors at application lebel.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DevOpsAPIErrorDescriptor objects
            found in the response.
    """

    text: str | None
    error_descriptors: list[DevOpsAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        httpx_error: httpx.HTTPStatusError,
        error_descriptors: list[DevOpsAPIErrorDescriptor],
    ) -> None:
        DevOpsAPIException.__init__(self, text)
        httpx.HTTPStatusError.__init__(
            self,
            message=str(httpx_error),
            request=httpx_error.request,
            response=httpx_error.response,
        )
        self.text = text
        self.httpx_error = httpx_error
        self.error_descriptors = error_descriptors

    def __str__(self) -> str:
        return self.text or str(self.httpx_error)

    @classmethod
    def from_httpx_error(
        cls,
        httpx_error: httpx.HTTPStatusError,
        **kwargs: Any,
    ) -> DevOpsAPIHttpException:
        """Parse a httpx status error into this exception."""

        dictforced_response: dict[str, Any]
        # the attempt to extract a response structure cannot afford failure.
        try:
            raw_response = httpx_error.response.json()
            if isinstance(raw_response, dict):
                dictforced_response = raw_response
            else:
                dictforced_response = {}
        except Exception:
            dictforced_response = {}
        error_descriptors = [
            DevOpsAPIErrorDescriptor(error_dict)
            for error_dict in dictforced_response.get("errors") or []
        ]
        if error_descriptors:
            text = f"{error_descriptors[0].message}. {str(httpx_error)}"
        else:
            text = str(httpx_error)

        return cls(
            text=text,
            httpx_error=httpx_error,
            error_descriptors=error_descriptors,
            **kwargs,
        )

A request to the DevOps API resulted in an HTTP 4xx or 5xx response.

Though the DevOps API seldom enriches such errors with a response text, this class acts as the DevOps counterpart to DataAPIHttpException to facilitate a symmetryc handling of errors at application lebel.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DevOpsAPIErrorDescriptor objects found in the response.

Ancestors

  • DevOpsAPIException
  • httpx.HTTPStatusError
  • httpx.HTTPError
  • builtins.Exception
  • builtins.BaseException

Static methods

def from_httpx_error(httpx_error: httpx.HTTPStatusError, **kwargs: Any) ‑> DevOpsAPIHttpException

Parse a httpx status error into this exception.

Instance variables

var error_descriptors : list[DevOpsAPIErrorDescriptor]

The type of the None singleton.

var text : str | None

The type of the None singleton.

class DevOpsAPIResponseException (text: str | None = None,
*,
command: dict[str, Any] | None = None,
error_descriptors: list[DevOpsAPIErrorDescriptor] = [])
Expand source code
class DevOpsAPIResponseException(DevOpsAPIException):
    """
    A request to the DevOps API returned with a non-success return code
    and one of more errors in the HTTP response.

    Attributes:
        text: a text message about the exception.
        command: the raw payload that was sent to the DevOps API.
        error_descriptors: a list of all DevOpsAPIErrorDescriptor objects
            returned by the API in the response.
    """

    text: str | None
    command: dict[str, Any] | None
    error_descriptors: list[DevOpsAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None = None,
        *,
        command: dict[str, Any] | None = None,
        error_descriptors: list[DevOpsAPIErrorDescriptor] = [],
    ) -> None:
        super().__init__(text or self.__class__.__name__)
        self.text = text
        self.command = command
        self.error_descriptors = error_descriptors

    @staticmethod
    def from_response(
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
    ) -> DevOpsAPIResponseException:
        """Parse a raw response from the API into this exception."""

        dictforced_response = raw_response if isinstance(raw_response, dict) else {}
        error_descriptors = [
            DevOpsAPIErrorDescriptor(error_dict)
            for error_dict in dictforced_response.get("errors") or []
        ]
        if error_descriptors:
            _text = error_descriptors[0].message
        else:
            _text = None
        return DevOpsAPIResponseException(
            text=_text, command=command, error_descriptors=error_descriptors
        )

A request to the DevOps API returned with a non-success return code and one of more errors in the HTTP response.

Attributes

text
a text message about the exception.
command
the raw payload that was sent to the DevOps API.
error_descriptors
a list of all DevOpsAPIErrorDescriptor objects returned by the API in the response.

Ancestors

Class variables

var command : dict[str, typing.Any] | None

The type of the None singleton.

var error_descriptors : list[DevOpsAPIErrorDescriptor]

The type of the None singleton.

var text : str | None

The type of the None singleton.

Static methods

def from_response(command: dict[str, Any] | None, raw_response: dict[str, Any]) ‑> DevOpsAPIResponseException
Expand source code
@staticmethod
def from_response(
    command: dict[str, Any] | None,
    raw_response: dict[str, Any],
) -> DevOpsAPIResponseException:
    """Parse a raw response from the API into this exception."""

    dictforced_response = raw_response if isinstance(raw_response, dict) else {}
    error_descriptors = [
        DevOpsAPIErrorDescriptor(error_dict)
        for error_dict in dictforced_response.get("errors") or []
    ]
    if error_descriptors:
        _text = error_descriptors[0].message
    else:
        _text = None
    return DevOpsAPIResponseException(
        text=_text, command=command, error_descriptors=error_descriptors
    )

Parse a raw response from the API into this exception.

class DevOpsAPITimeoutException (text: str, *, timeout_type: str, endpoint: str | None, raw_payload: str | None)
Expand source code
@dataclass
class DevOpsAPITimeoutException(DevOpsAPIException):
    """
    A DevOps API operation timed out.

    Attributes:
        text: a textual description of the error
        timeout_type: this denotes the phase of the HTTP request when the event
            occurred ("connect", "read", "write", "pool") or "generic" if there is
            not a specific request associated to the exception.
        endpoint: if the timeout is tied to a specific request, this is the
            URL that the request was targeting.
        raw_payload:  if the timeout is tied to a specific request, this is the
            associated payload (as a string).
    """

    text: str
    timeout_type: str
    endpoint: str | None
    raw_payload: str | None

    def __init__(
        self,
        text: str,
        *,
        timeout_type: str,
        endpoint: str | None,
        raw_payload: str | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.timeout_type = timeout_type
        self.endpoint = endpoint
        self.raw_payload = raw_payload

A DevOps API operation timed out.

Attributes

text
a textual description of the error
timeout_type
this denotes the phase of the HTTP request when the event occurred ("connect", "read", "write", "pool") or "generic" if there is not a specific request associated to the exception.
endpoint
if the timeout is tied to a specific request, this is the URL that the request was targeting.
raw_payload
if the timeout is tied to a specific request, this is the associated payload (as a string).

Ancestors

Instance variables

var endpoint : str | None

The type of the None singleton.

var raw_payload : str | None

The type of the None singleton.

var text : str

The type of the None singleton.

var timeout_type : str

The type of the None singleton.

class TableInsertManyException (inserted_ids: list[Any],
inserted_id_tuples: list[tuple[Any, ...]],
exceptions: Sequence[Exception])
Expand source code
@dataclass
class TableInsertManyException(DataAPIException):
    """
    An exception occurring within an insert_many (an operation that can span
    several requests). As such, it represents both the root error(s) that happened
    and information on the portion of the row that were successfully inserted.

    The behaviour of insert_many (concurrency and the `ordered` setting) make it
    possible that more than one "root errors" are collected.

    Attributes:
        inserted_ids: a list of the row IDs that have been successfully inserted,
            in the form of a dictionary matching the table primary key).
        inserted_id_tuples: the same information as for `inserted_ids` (in the same
            order), but in form of a tuples for each ID.
        exceptions: a list of the root exceptions leading to this error. The list,
            under normal circumstances, is not empty.
    """

    inserted_ids: list[Any]
    inserted_id_tuples: list[tuple[Any, ...]]
    exceptions: Sequence[Exception]

    def __str__(self) -> str:
        num_ids = len(self.inserted_ids)
        if self.exceptions:
            exc_desc: str
            excs_strs = [exc.__str__() for exc in self.exceptions[:8]]
            if len(self.exceptions) > 8:
                exc_desc = ", ".join(excs_strs) + " ... (more exceptions)"
            else:
                exc_desc = ", ".join(excs_strs)
            return (
                f"{self.__class__.__name__}({exc_desc} [with {num_ids} inserted ids])"
            )
        else:
            return f"{self.__class__.__name__}()"

An exception occurring within an insert_many (an operation that can span several requests). As such, it represents both the root error(s) that happened and information on the portion of the row that were successfully inserted.

The behaviour of insert_many (concurrency and the ordered setting) make it possible that more than one "root errors" are collected.

Attributes

inserted_ids
a list of the row IDs that have been successfully inserted, in the form of a dictionary matching the table primary key).
inserted_id_tuples
the same information as for inserted_ids (in the same order), but in form of a tuples for each ID.
exceptions
a list of the root exceptions leading to this error. The list, under normal circumstances, is not empty.

Ancestors

Instance variables

var exceptions : Sequence[Exception]

The type of the None singleton.

var inserted_id_tuples : list[tuple[typing.Any, ...]]

The type of the None singleton.

var inserted_ids : list[typing.Any]

The type of the None singleton.

class TooManyDocumentsToCountException (text: str, *, server_max_count_exceeded: bool)
Expand source code
@dataclass
class TooManyDocumentsToCountException(DataAPIException):
    """
    A `count_documents()` operation on a collection failed because the resulting
    number of documents exceeded either the upper bound set by the caller or the
    hard limit imposed by the Data API.

    Attributes:
        text: a text message about the exception.
        server_max_count_exceeded: True if the count limit imposed by the API
            is reached. In that case, increasing the upper bound in the method
            invocation is of no help.
    """

    text: str
    server_max_count_exceeded: bool

    def __init__(
        self,
        text: str,
        *,
        server_max_count_exceeded: bool,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.server_max_count_exceeded = server_max_count_exceeded

A count_documents() operation on a collection failed because the resulting number of documents exceeded either the upper bound set by the caller or the hard limit imposed by the Data API.

Attributes

text
a text message about the exception.
server_max_count_exceeded
True if the count limit imposed by the API is reached. In that case, increasing the upper bound in the method invocation is of no help.

Ancestors

Instance variables

var server_max_count_exceeded : bool

The type of the None singleton.

var text : str

The type of the None singleton.

class TooManyRowsToCountException (text: str, *, server_max_count_exceeded: bool)
Expand source code
@dataclass
class TooManyRowsToCountException(DataAPIException):
    """
    A `count_documents()` operation on a table failed because of the excessive amount
    of rows to count.

    Attributes:
        text: a text message about the exception.
    """

    text: str
    server_max_count_exceeded: bool

    def __init__(
        self,
        text: str,
        *,
        server_max_count_exceeded: bool,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.server_max_count_exceeded = server_max_count_exceeded

A count_documents() operation on a table failed because of the excessive amount of rows to count.

Attributes

text
a text message about the exception.

Ancestors

Instance variables

var server_max_count_exceeded : bool

The type of the None singleton.

var text : str

The type of the None singleton.

class UnexpectedDataAPIResponseException (text: str, raw_response: dict[str, Any] | None)
Expand source code
@dataclass
class UnexpectedDataAPIResponseException(DataAPIException):
    """
    The Data API response is malformed in that it does not have
    expected field(s), or they are of the wrong type.

    Attributes:
        text: a text message about the exception.
        raw_response: the response returned by the API in the form of a dict.
    """

    text: str
    raw_response: dict[str, Any] | None

    def __init__(
        self,
        text: str,
        raw_response: dict[str, Any] | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.raw_response = raw_response

The Data API response is malformed in that it does not have expected field(s), or they are of the wrong type.

Attributes

text
a text message about the exception.
raw_response
the response returned by the API in the form of a dict.

Ancestors

Instance variables

var raw_response : dict[str, typing.Any] | None

The type of the None singleton.

var text : str

The type of the None singleton.

class UnexpectedDevOpsAPIResponseException (text: str, raw_response: dict[str, Any] | None)
Expand source code
@dataclass
class UnexpectedDevOpsAPIResponseException(DevOpsAPIException):
    """
    The DevOps API response is malformed in that it does not have
    expected field(s), or they are of the wrong type.

    Attributes:
        text: a text message about the exception.
        raw_response: the response returned by the API in the form of a dict.
    """

    text: str
    raw_response: dict[str, Any] | None

    def __init__(
        self,
        text: str,
        raw_response: dict[str, Any] | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.raw_response = raw_response

The DevOps API response is malformed in that it does not have expected field(s), or they are of the wrong type.

Attributes

text
a text message about the exception.
raw_response
the response returned by the API in the form of a dict.

Ancestors

Instance variables

var raw_response : dict[str, typing.Any] | None

The type of the None singleton.

var text : str

The type of the None singleton.