跳转至

Exceptions

HTTPError

Bases: Exception

The exception to end the request handling and return an JSON error response.

Examples:

from apiflask import APIFlask, HTTPError
from markupsafe import escape

app = APIFlask(__name__)

@app.get('/<name>')
def hello(name):
    if name == 'Foo':
        raise HTTPError(404, 'This man is missing.')
    return f'Hello, escape{name}'!
Source code in apiflask/exceptions.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class HTTPError(Exception):
    """The exception to end the request handling and return an JSON error response.

    Examples:

    ```python
    from apiflask import APIFlask, HTTPError
    from markupsafe import escape

    app = APIFlask(__name__)

    @app.get('/<name>')
    def hello(name):
        if name == 'Foo':
            raise HTTPError(404, 'This man is missing.')
        return f'Hello, escape{name}'!
    ```
    """
    status_code: int = 500
    message: t.Optional[str] = None
    detail: t.Any = {}
    headers: ResponseHeaderType = {}
    extra_data: t.Mapping[str, t.Any] = {}

    def __init__(
        self,
        status_code: t.Optional[int] = None,
        message: t.Optional[str] = None,
        detail: t.Optional[t.Any] = None,
        headers: t.Optional[ResponseHeaderType] = None,
        extra_data: t.Optional[t.Mapping[str, t.Any]] = None
    ) -> None:
        """Initialize the error response.

        Arguments:
            status_code: The status code of the error (4XX and 5xx), defaults to 500.
            message: The simple description of the error. If not provided,
                the reason phrase of the status code will be used.
            detail: The detailed information of the error, you can use it to
                provide the addition information such as custom error code,
                documentation URL, etc.
            headers: A dict of headers used in the error response.
            extra_data: A dict of additional fields (custom error information) that will
                added to the error response body.

        *Version changed: 0.9.0*

        - Set `detail` and `headers` to empty dict if not set.

        *Version changed: 0.10.0*

        - Add `extra_data` parameter to accept additional error information.

        *Version changed: 0.11.0*

        - Change `status_code` from position argument to keyword argument, defaults to 500.
          Add class attributes with default values to support error subclasses.
        """
        super().__init__()
        if status_code is not None:
            # TODO: support use custom error status code?
            if status_code not in default_exceptions:
                raise LookupError(
                    f'No exception for status code {status_code!r}, '
                    ' valid error status code are "4XX" and "5XX".'
                )
            self.status_code = status_code
        if detail is not None:
            self.detail = detail
        if headers is not None:
            self.headers = headers
        if message is not None:
            self.message = message
        if extra_data is not None:
            self.extra_data = extra_data

        if self.message is None:
            # make sure the error message is not empty
            self.message: str = get_reason_phrase(self.status_code, 'Unknown error')

__init__(status_code=None, message=None, detail=None, headers=None, extra_data=None)

Initialize the error response.

Parameters:

Name Type Description Default
status_code Optional[int]

The status code of the error (4XX and 5xx), defaults to 500.

None
message Optional[str]

The simple description of the error. If not provided, the reason phrase of the status code will be used.

None
detail Optional[Any]

The detailed information of the error, you can use it to provide the addition information such as custom error code, documentation URL, etc.

None
headers Optional[ResponseHeaderType]

A dict of headers used in the error response.

None
extra_data Optional[Mapping[str, Any]]

A dict of additional fields (custom error information) that will added to the error response body.

None

Version changed: 0.9.0

  • Set detail and headers to empty dict if not set.

Version changed: 0.10.0

  • Add extra_data parameter to accept additional error information.

Version changed: 0.11.0

  • Change status_code from position argument to keyword argument, defaults to 500. Add class attributes with default values to support error subclasses.
Source code in apiflask/exceptions.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def __init__(
    self,
    status_code: t.Optional[int] = None,
    message: t.Optional[str] = None,
    detail: t.Optional[t.Any] = None,
    headers: t.Optional[ResponseHeaderType] = None,
    extra_data: t.Optional[t.Mapping[str, t.Any]] = None
) -> None:
    """Initialize the error response.

    Arguments:
        status_code: The status code of the error (4XX and 5xx), defaults to 500.
        message: The simple description of the error. If not provided,
            the reason phrase of the status code will be used.
        detail: The detailed information of the error, you can use it to
            provide the addition information such as custom error code,
            documentation URL, etc.
        headers: A dict of headers used in the error response.
        extra_data: A dict of additional fields (custom error information) that will
            added to the error response body.

    *Version changed: 0.9.0*

    - Set `detail` and `headers` to empty dict if not set.

    *Version changed: 0.10.0*

    - Add `extra_data` parameter to accept additional error information.

    *Version changed: 0.11.0*

    - Change `status_code` from position argument to keyword argument, defaults to 500.
      Add class attributes with default values to support error subclasses.
    """
    super().__init__()
    if status_code is not None:
        # TODO: support use custom error status code?
        if status_code not in default_exceptions:
            raise LookupError(
                f'No exception for status code {status_code!r}, '
                ' valid error status code are "4XX" and "5XX".'
            )
        self.status_code = status_code
    if detail is not None:
        self.detail = detail
    if headers is not None:
        self.headers = headers
    if message is not None:
        self.message = message
    if extra_data is not None:
        self.extra_data = extra_data

    if self.message is None:
        # make sure the error message is not empty
        self.message: str = get_reason_phrase(self.status_code, 'Unknown error')

abort(status_code, message=None, detail=None, headers=None, extra_data=None)

A function to raise HTTPError exception.

Similar to Flask's abort, but returns a JSON response.

Examples:

from apiflask import APIFlask, abort
from markupsafe import escape

app = APIFlask(__name__)

@app.get('/<name>')
def hello(name):
    if name == 'Foo':
        abort(404, 'This man is missing.')
        # or just `abort(404)`
    return f'Hello, escape{name}'!

P.S. When app.json_errors is True (default), Flask's flask.abort will also return JSON error response.

Parameters:

Name Type Description Default
status_code int

The status code of the error (4XX and 5xx).

required
message Optional[str]

The simple description of the error. If not provided, the reason phrase of the status code will be used.

None
detail Optional[Any]

The detailed information of the error, you can use it to provide the addition information such as custom error code, documentation URL, etc.

None
headers Optional[ResponseHeaderType]

A dict of headers used in the error response.

None
extra_data Optional[dict]

A dict of additional fields (custom error information) that will added to the error response body.

None

Version changed: 0.4.0

  • Rename the function name from abort_json to abort.

Version changed: 0.10.0

  • Add new parameter extra_data.
Source code in apiflask/exceptions.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def abort(
    status_code: int,
    message: t.Optional[str] = None,
    detail: t.Optional[t.Any] = None,
    headers: t.Optional[ResponseHeaderType] = None,
    extra_data: t.Optional[dict] = None
) -> None:
    """A function to raise HTTPError exception.

    Similar to Flask's `abort`, but returns a JSON response.

    Examples:

    ```python
    from apiflask import APIFlask, abort
    from markupsafe import escape

    app = APIFlask(__name__)

    @app.get('/<name>')
    def hello(name):
        if name == 'Foo':
            abort(404, 'This man is missing.')
            # or just `abort(404)`
        return f'Hello, escape{name}'!
    ```

    P.S. When `app.json_errors` is `True` (default), Flask's `flask.abort` will also
    return JSON error response.

    Arguments:
        status_code: The status code of the error (4XX and 5xx).
        message: The simple description of the error. If not provided,
            the reason phrase of the status code will be used.
        detail: The detailed information of the error, you can use it to
            provide the addition information such as custom error code,
            documentation URL, etc.
        headers: A dict of headers used in the error response.
        extra_data: A dict of additional fields (custom error information) that will
            added to the error response body.

    *Version changed: 0.4.0*

    - Rename the function name from `abort_json` to `abort`.

    *Version changed: 0.10.0*

    - Add new parameter `extra_data`.
    """
    raise HTTPError(status_code, message, detail, headers, extra_data)