The exception to end the request handling and return an JSON error response.
Examples:
fromapiflaskimportAPIFlask,HTTPErrorfrommarkupsafeimportescapeapp=APIFlask(__name__)@app.get('/<name>')defhello(name):ifname=='Foo':raiseHTTPError(404,'This man is missing.')returnf'Hello, escape{name}'!
classHTTPError(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=500message:str|None=Nonedetail:t.Any={}headers:ResponseHeaderType={}extra_data:t.Mapping[str,t.Any]={}def__init__(self,status_code:int|None=None,message:str|None=None,detail:t.Any|None=None,headers:ResponseHeaderType|None=None,extra_data:t.Mapping[str,t.Any]|None=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__()ifstatus_codeisnotNone:# TODO: support use custom error status code?ifstatus_codenotindefault_exceptions:raiseLookupError(f'No exception for status code {status_code!r},'' valid error status code are "4XX" and "5XX".')self.status_code=status_codeifdetailisnotNone:self.detail=detailifheadersisnotNone:self.headers=headersifmessageisnotNone:self.message=messageifextra_dataisnotNone:self.extra_data=extra_dataifself.messageisNone:# make sure the error message is not emptyself.message:str=get_reason_phrase(self.status_code,'Unknown error')
def__init__(self,status_code:int|None=None,message:str|None=None,detail:t.Any|None=None,headers:ResponseHeaderType|None=None,extra_data:t.Mapping[str,t.Any]|None=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__()ifstatus_codeisnotNone:# TODO: support use custom error status code?ifstatus_codenotindefault_exceptions:raiseLookupError(f'No exception for status code {status_code!r},'' valid error status code are "4XX" and "5XX".')self.status_code=status_codeifdetailisnotNone:self.detail=detailifheadersisnotNone:self.headers=headersifmessageisnotNone:self.message=messageifextra_dataisnotNone:self.extra_data=extra_dataifself.messageisNone:# make sure the error message is not emptyself.message:str=get_reason_phrase(self.status_code,'Unknown error')
Similar to Flask's abort, but returns a JSON response.
Examples:
fromapiflaskimportAPIFlask,abortfrommarkupsafeimportescapeapp=APIFlask(__name__)@app.get('/<name>')defhello(name):ifname=='Foo':abort(404,'This man is missing.')# or just `abort(404)`returnf'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
str | None
The simple description of the error. If not provided,
the reason phrase of the status code will be used.
None
detail
Any | None
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
ResponseHeaderType | None
A dict of headers used in the error response.
None
extra_data
dict | None
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.
defabort(status_code:int,message:str|None=None,detail:t.Any|None=None,headers:ResponseHeaderType|None=None,extra_data:dict|None=None,)->t.NoReturn:"""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`. """raiseHTTPError(status_code,message,detail,headers,extra_data)