import re import sys from flask import current_app, got_request_exception from flask_restful import Api, http_status_message from werkzeug.datastructures import Headers from werkzeug.exceptions import HTTPException from core.errors.error import AppInvokeQuotaExceededError class ExternalApi(Api): def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception """ got_request_exception.send(current_app, exception=e) headers = Headers() if isinstance(e, HTTPException): if e.response is not None: resp = e.get_response() return resp status_code = e.code default_data = { 'code': re.sub(r'(?= 500: exc_info = sys.exc_info() if exc_info[1] is None: exc_info = None current_app.log_exception(exc_info) if status_code == 406 and self.default_mediatype is None: # if we are handling NotAcceptable (406), make sure that # make_response uses a representation we support as the # default mediatype (so that make_response doesn't throw # another NotAcceptable error). supported_mediatypes = list(self.representations.keys()) # only supported application/json fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain" data = { 'code': 'not_acceptable', 'message': data.get('message') } resp = self.make_response( data, status_code, headers, fallback_mediatype = fallback_mediatype ) elif status_code == 400: if isinstance(data.get('message'), dict): param_key, param_value = list(data.get('message').items())[0] data = { 'code': 'invalid_param', 'message': param_value, 'params': param_key } else: if 'code' not in data: data['code'] = 'unknown' resp = self.make_response(data, status_code, headers) else: if 'code' not in data: data['code'] = 'unknown' resp = self.make_response(data, status_code, headers) if status_code == 401: resp = self.unauthorized(resp) return resp