From e371ed69bb00f1114fa2aa5deb41bf86a539841b Mon Sep 17 00:00:00 2001 From: Jake Moshenko Date: Thu, 6 Apr 2017 18:46:44 -0400 Subject: [PATCH] Fix for flask-restful >0.3 error handling --- endpoints/api/__init__.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/endpoints/api/__init__.py b/endpoints/api/__init__.py index 0e876f21b..becc1be3a 100644 --- a/endpoints/api/__init__.py +++ b/endpoints/api/__init__.py @@ -30,22 +30,28 @@ from util.pagination import encrypt_page_token, decrypt_page_token logger = logging.getLogger(__name__) api_bp = Blueprint('api', __name__) -api = Api() + + +class ApiExceptionHandlingApi(Api): + @crossdomain(origin='*', headers=['Authorization', 'Content-Type']) + def handle_error(self, error): + if isinstance(error, ApiException): + response = Response(json.dumps(error.to_dict()), error.status_code, + mimetype='application/json') + if error.status_code == 401: + response.headers['WWW-Authenticate'] = ('Bearer error="%s" error_description="%s"' % + (error.error_type.value, error.error_description)) + return response + return super(ApiExceptionHandlingApi, self).handle_error(error) + + +api = ApiExceptionHandlingApi() api.init_app(api_bp) api.decorators = [csrf_protect(), crossdomain(origin='*', headers=['Authorization', 'Content-Type']), process_oauth, time_decorator(api_bp.name, metric_queue)] -@api_bp.app_errorhandler(ApiException) -@crossdomain(origin='*', headers=['Authorization', 'Content-Type']) -def handle_api_error(error): - response = Response(json.dumps(error.to_dict()), error.status_code, mimetype='application/json') - if error.status_code == 401: - response.headers['WWW-Authenticate'] = ('Bearer error="%s" error_description="%s"' % - (error.error_type.value, error.error_description)) - return response - def resource(*urls, **kwargs): def wrapper(api_resource): if not api_resource: