trolldb.errors.errors module

The module which defines the base functionalities for errors that will be raised when using the package or the API.

This module only includes the generic utilities using which each module should define its own error responses specifically. See trolldb.database.errors as an example on how to achieve this.

trolldb.errors.errors.StatusCode

An alias for the built-in int type, which is used for HTTP status codes.

trolldb.errors.errors._listify(item: str | list[str]) list[str][source]

Encloses the given (single) string in a list or returns the same input as-is in case of a list of strings.

Parameters:

item – The item that needs to be converted to a list.

Returns:

If the input is itself a list of strings the same list is returned as-is, otherwise, the given input string is enclosed in [] and returned.

Example

# The following evaluate to True
_listify("test") == ["test"]
_listify(["a", "b"]) = ["a", "b"]
_listify([]) == []
trolldb.errors.errors._stringify(item: str | list[str], delimiter: str) str[source]

Makes a single string out of the item(s) by delimiting them with delimiter.

Parameters:
  • item – A string or list of strings to be delimited.

  • delimiter – A string as delimiter.

Returns:

The same input string, or in case of a list of items, a single string delimited by delimiter.

exception trolldb.errors.errors.ResponseError(args_dict: OrderedDict[int, str | list[str]] | dict)[source]

Bases: Exception

The base class for all error responses.

This is a derivative of the Exception class and therefore can be used directly in raise statements.

__dict

An ordered dictionary in which the keys are (HTTP) status codes and the values are the corresponding messages.

Type:

OrderedDict[StatusCode, str]

descriptor_delimiter: ClassVar[str] = ' |OR| '

A delimiter to divide the message part of several error responses which have been combined into a single one.

This will be shown in textual format for the response descriptors of the Fast API routes.

Example

error_a = ResponseError({400: "Bad Request"})
error_b = ResponseError({404: "Not Found"})
errors = error_a | error_b

# When used in a FastAPI response descriptor, the following string is generated
"Bad Request |OR| Not Found"
DefaultResponseClass: ClassVar[fastapi.Response]

The default type of the response which will be returned when an error occurs.

This must be a valid member (class) of fastapi.responses.

__init__(args_dict: OrderedDict[int, str | list[str]] | dict) None[source]

Initializes the error object given a dictionary of error (HTTP) codes (keys) and messages (values).

Note

The order of items will be preserved as we use an ordered dictionary to store the items internally.

Example

# The following are all valid error objects
error_a = ResponseError({400: "Bad Request"})
error_b = ResponseError({404: "Not Found"})
errors = error_a | error_b
errors_a_or_b = ResponseError({400: "Bad Request", 404: "Not Found"})
errors_list = ResponseError({404: ["Not Found", "Yet Not Found"]})
__or__(other: Self) Self[source]

Implements the bitwise or | which combines the error objects into a single error response.

Parameters:

other – Another error response of the same base type to combine with.

Returns:

A new error response which includes the combined error response. In case of different (HTTP) status codes, the returned response includes the {<status-code>: <message>} pairs for both self and the other. In case of the same status codes, the messages will be combined into a list.

Example

error_a = ResponseError({400: "Bad Request"})
error_b = ResponseError({404: "Not Found"})
error_c = ResponseError({400: "Still Bad Request"})

errors_combined = error_a | error_b | error_c

# which is equivalent to the following
errors_combined_literal = ResponseError({
    400: ["Bad Request", "Still Bad Request"],
    404: "Not Found"
}
__retrieve_one_from_some(status_code: int | None = None) tuple[int, str]

Retrieves a tuple (<status-code>, <message>) from the internal dictionary ResponseError.__dict.

Parameters:

status_code (Optional, default None) – The status code to retrieve from the internal dictionary. In case of None, the internal dictionary must include only a single entry which will be returned.

Returns:

The tuple of (<status-code>, <message>).

Raises:
  • ValueError – In case of ambiguity, i.e. there are multiple items in the internal dictionary and the status_code is None.

  • KeyError – When the given status_code cannot be found.

get_error_details(extra_information: dict | None = None, status_code: int | None = None) tuple[int, str][source]

Gets the details of the error response.

Parameters:
  • extra_information (Optional, default None) – More information (if any) that needs to be added to the message string.

  • status_code (Optional, default None) – The status code to retrieve. This is useful when there are several error items in the internal dictionary. In case of None, the internal dictionary must include a single entry, otherwise an error is raised.

Returns:

A tuple, in which the first element is the status code and the second element is a single string message.

log_as_warning(extra_information: dict | None = None, status_code: int | None = None) None[source]

Same as get_error_details() but logs the error as a warning and returns None.

sys_exit_log(exit_code: int = -1, extra_information: dict | None = None, status_code: int | None = None) NoReturn[source]

Same as get_error_details() but logs the error and calls the sys.exit.

The arguments are the same as get_error_details() with the addition of exit_code which is optional and is set to -1 by default.

Warning

This is supposed to be done in case of non-recoverable errors, e.g. database issues. For other cases, we try to see if we can recover and continue.

Returns:

Does not return anything, but logs the error and exits the program.

property fastapi_descriptor: dict[int, dict[str, str]]

Gets the FastAPI descriptor (dictionary) of the error items stored in ResponseError.__dict.

Note

Consult the FastAPI documentation for additional responses to see why and how descriptors are used.

Example

error_a = ResponseError({400: "Bad Request"})
error_b = ResponseError({404: "Not Found"})
error_c = ResponseError({400: "Still Bad Request"})

errors_combined = error_a | error_b | error_c
errors_combined.fastapi_descriptor == {
    400: {"description": "Bad Request |OR| Still Bad Request"},
    404: {"description": "Not Found"}
}
class trolldb.errors.errors.ResponsesErrorGroup[source]

Bases: object

A class which groups related errors.

This provides a base class from which actual error groups are derived. The attributes of this class are all static.

See trolldb.database.errors as an example on how to achieve this.

classmethod members() dict[str, ResponseError][source]

Retrieves a dictionary of all errors which are members of the class.

classmethod union() ResponseError[source]

Gets the union of all member errors in the group.

This is useful when one wants to get the FastAPI response descriptor of all members. This function utilizes the bitwise or | functionality of ResponseError.