Skip to content

Commit

Permalink
Use json for error response of REST api
Browse files Browse the repository at this point in the history
This uses application/json for error response too. With this, all REST
api return application/json except 404 error (we can't use
@blueprint.errorhandler(404) for now) and ItemDownloadView
(ItemDownloadView uses "Content-Type" as downloaded data type).
  • Loading branch information
OGAWAHirofumi committed Nov 3, 2020
1 parent a90b0f0 commit f991fb7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/bepasty/apis/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,22 @@
# "/lodgeit/" in the same blueprint and there is no way to exclude
# from using the same error handler ("/lodgeit/" is not REST api).
def rest_errorhandler(func):
def error_message(description, code):
return jsonify({
'error': {'code': code, 'message': description},
}), code

def handler(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPException as exc:
return exc.description, exc.code
return error_message(exc.description, exc.code)
except Exception:
if current_app.propagate_exceptions:
# if testing/debug mode, re-raise
raise
exc = InternalServerError()
return exc.description, exc.code
return error_message(exc.description, exc.code)

return handler

Expand Down
4 changes: 3 additions & 1 deletion src/bepasty/tests/test_rest_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ def check_response(response, code, ftype='application/json', check_data=True):


def check_err_response(response, code, check_data=True):
check_response(response, code, 'text/html; charset=utf-8', check_data)
check_response(response, code, check_data=check_data)
if check_data:
assert code == response.json['error']['code']
# check if doesn't have html tag
assert not re.match(r'<.+>', response.data.decode())

Expand Down

0 comments on commit f991fb7

Please sign in to comment.