File: errors.py

package info (click to toggle)
python-aioridwell 2024.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 396 kB
  • sloc: python: 1,062; sh: 41; makefile: 5
file content (54 lines) | stat: -rw-r--r-- 1,212 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Define package exceptions."""
from __future__ import annotations

from typing import Any


class RidwellError(Exception):
    """Define a base exception."""

    pass


class InvalidCredentialsError(RidwellError):
    """Define an error related to a bad credentials."""

    pass


class RequestError(RidwellError):
    """Define an error related to a bad HTTP request."""

    pass


class TokenExpiredError(RidwellError):
    """Define an error related to an expired token."""

    pass


DATA_ERROR_MAP = {
    "The password you entered is incorrect. Please try again.": InvalidCredentialsError,
    "login required": TokenExpiredError,
}


def raise_for_data_error(data: dict[str, Any]) -> None:
    """Raise an appropriate error if a message exists in the response data.

    Args:
        data: An API response payload.

    Raises:
        exc: A RidwellError subclass.
    """
    if "errors" not in data:
        return

    # A response payload may feasibly contain several errors (based on its JSON
    # structure), so we only handle the first one:
    first_error = data["errors"][0]
    message = first_error["message"]
    exc = DATA_ERROR_MAP.get(message, RequestError)
    raise exc(message)