Update format of the errors for DataError and exception

This commit is contained in:
Rebecca Law
2016-11-10 14:53:39 +00:00
parent 26d6a0c1a9
commit 7d763260ce
2 changed files with 33 additions and 5 deletions

View File

@@ -1,10 +1,8 @@
import json
from flask import jsonify, current_app
from jsonschema import ValidationError
from sqlalchemy.exc import DataError
from sqlalchemy.orm.exc import NoResultFound
from app.authentication.auth import AuthError
from app.errors import InvalidRequest
@@ -42,7 +40,8 @@ def register_errors(blueprint):
@blueprint.errorhandler(DataError)
def no_result_found(e):
current_app.logger.exception(e)
return jsonify(message="No result found"), 404
return jsonify(status_code=404,
errors=[{"error": e.__class__.__name__, "message": "No result found"}]), 404
@blueprint.errorhandler(AuthError)
def auth_error(error):
@@ -51,4 +50,5 @@ def register_errors(blueprint):
@blueprint.errorhandler(Exception)
def internal_server_error(error):
current_app.logger.exception(error)
return jsonify(message='Internal server error'), 500
return jsonify(status_code=500,
errors=[{"error": error.__class__.__name__, "message": 'Internal server error'}]), 500

View File

@@ -1,7 +1,7 @@
import json
import pytest
from flask import url_for
from sqlalchemy.exc import DataError
@pytest.fixture(scope='function')
@@ -35,6 +35,14 @@ def app_for_test(mocker):
from app.v2.notifications.notification_schemas import post_sms_request
validate({"template_id": "bad_uuid"}, post_sms_request)
@blue.route("raise_data_error", methods=["GET"])
def raising_data_error():
raise DataError("There was a db problem", "params", "orig")
@blue.route("raise_exception", methods=["GET"])
def raising_exception():
raise AssertionError("Raising any old exception")
register_errors(blue)
app.register_blueprint(blue)
@@ -87,3 +95,23 @@ def test_validation_error(app_for_test):
'message': {'phone_number': 'is a required property'}} in error['errors']
assert {'error': 'ValidationError',
'message': {'template_id': 'not a valid UUID'}} in error['errors']
def test_data_errors(app_for_test):
with app_for_test.test_request_context():
with app_for_test.test_client() as client:
response = client.get(url_for('v2_under_test.raising_data_error'))
assert response.status_code == 404
error = json.loads(response.get_data(as_text=True))
assert error == {"status_code": 404,
"errors": [{"error": "DataError", "message": "No result found"}]}
def test_internal_server_error_handler(app_for_test):
with app_for_test.test_request_context():
with app_for_test.test_client() as client:
response = client.get(url_for("v2_under_test.raising_exception"))
assert response.status_code == 500
error = json.loads(response.get_data(as_text=True))
assert error == {"status_code": 500,
"errors": [{"error": "AssertionError", "message": "Internal server error"}]}