from flask import jsonify from structlog import getLogger from werkzeug.exceptions import NotFound from delphi_api.errors import Codes, ItemNotFoundError LOG = getLogger(__name__) def handle_generic_error(ex): """Generic error handler""" LOG.exception(ex) response = jsonify(ex.error) response.status_code = ex.status_code response.content_type = 'application/json' return response def handle_not_found_error(ex: NotFound): """NotFound error handler""" response = jsonify({ 'code': Codes.item_not_found.value, 'description': 'The item you searched for could not be found.' }) response.status_code = 404 response.content_type = 'application/json' return response def handle_unchecked_exception(ex): """Blanket handle any unchecked application exceptions so they return a JSON response""" LOG.exception(ex) response = jsonify({ 'code': Codes.internal_error.value, 'description': 'The application encountered an internal error. ' 'The team has been notified of this issue.', 'details': str(ex), }) response.status_code = 500 response.content_type = 'application/json' return response def handle_auth_error(ex): """Handles the error response for ``AuthError`` exceptions""" return handle_generic_error(ex) def handle_invalid_input_error(ex): """Handles the error response for ``InvalidInputError`` exceptions""" return handle_generic_error(ex) def handle_proto_binary_attribute_error(ex): """Handles the error response for ``ProtoBinaryAttributeError`` exceptions""" return handle_generic_error(ex) def handle_not_implemented_error(ex: NotImplementedError): """Handles the error response for ``NotImplementedError``""" LOG.exception(ex) response = jsonify({ 'code': Codes.not_implemented.value, 'description': 'This feature has not yet been implemented.', 'details': str(ex), }) response.status_code = 501 response.content_type = 'application/json' return response