werkzeug.exceptions.BadRequest (400) is converted to internal server error (500)
Talkless opened this issue · comments
Vincas Dargis commented
If we have:
@jsonrpc.method('MyApp.index')
@jwt_required()
def index(name: str) -> str:
raise werkzeug.exceptions.BadRequest("bad parameter")
In result we get (from console output of Flask server):
<..backtrace..>
werkzeug.exceptions.BadRequest: 400 Bad Request: bad parameter
127.0.0.1 - - [06/Sep/2022 15:48:52] "POST /myapi HTTP/1.1" 500 -
requests.post()
and then .raise_for_status()
results in:
requests.exceptions.HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: http://127.0.0.1:5000/myapi
It would be nice to be able to validate parameters ourselves, and respond with appropriate error codes and messages to the API user.
Nycholas Oliveira commented
Hi @Talkless,
Yes, according to JSON-RPC specification, every code errors are here[1], and there is a range of custom errors:
-32000 to -32099 | Server error | Reserved for implementation-defined server-errors.
You can use the JSONRPCError[2] to do it, for example:
error = JSONRPCError(message="I'm a teapot", code=-32768, data={'data': [1, 2, 3]}, status_code=418)
assert error.code == -32768
assert error.message == "I'm a teapot"
assert error.data == {'data': [1, 2, 3]}
assert error.status_code == 418
assert error.jsonrpc_format == {
'code': -32768,
'data': {'data': [1, 2, 3]},
'message': "I'm a teapot",
'name': 'JSONRPCError',
}
[1] - https://www.jsonrpc.org/specification#error_object
[2] - https://github.com/cenobites/flask-jsonrpc/blob/master/src/flask_jsonrpc/exceptions.py#L41