From f991fb78ef916dbde0ebf30c2763beebc9aaa6b9 Mon Sep 17 00:00:00 2001 From: OGAWA Hirofumi Date: Wed, 4 Nov 2020 06:06:23 +0900 Subject: [PATCH] Use json for error response of REST api 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). --- src/bepasty/apis/rest.py | 9 +++++++-- src/bepasty/tests/test_rest_server.py | 4 +++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/bepasty/apis/rest.py b/src/bepasty/apis/rest.py index f510208a..6693f56f 100644 --- a/src/bepasty/apis/rest.py +++ b/src/bepasty/apis/rest.py @@ -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 diff --git a/src/bepasty/tests/test_rest_server.py b/src/bepasty/tests/test_rest_server.py index f0a20a35..66c66ccd 100644 --- a/src/bepasty/tests/test_rest_server.py +++ b/src/bepasty/tests/test_rest_server.py @@ -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())