From 62725bb77398b513b996c8cdf97c41cabc0dc960 Mon Sep 17 00:00:00 2001 From: Ryan Petrello Date: Fri, 6 Sep 2013 18:02:49 -0400 Subject: [PATCH] Add improved support for HTTP response codes in cornice apps. Change-Id: I35efe85794e761877edd06722952292a3cac5d85 --- tests/test_cornice.py | 20 ++++++++++++++++++++ wsmeext/cornice.py | 15 +++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tests/test_cornice.py b/tests/test_cornice.py index 7cc2b85..b950a39 100644 --- a/tests/test_cornice.py +++ b/tests/test_cornice.py @@ -6,6 +6,7 @@ import webtest from cornice import Service from cornice import resource from pyramid.config import Configurator +from pyramid.httpexceptions import HTTPUnauthorized from wsme.types import text, Base, HostRequest from wsmeext.cornice import signature @@ -31,6 +32,15 @@ def users_create(data): return data +secret = Service(name='secrets', path='/secret') + + +@secret.get() +@signature() +def secret_get(): + raise HTTPUnauthorized() + + divide = Service(name='divide', path='/divide') @@ -163,3 +173,13 @@ class WSMECorniceTestCase(unittest.TestCase): print resp.body self.assertEquals(resp.json['faultcode'], 'Client') self.assertEquals(resp.status_code, 400) + + def test_runtime_error(self): + resp = self.app.get( + '/secret', + headers={'Accept': 'application/json'}, + expect_errors=True + ) + print resp.body + self.assertEquals(resp.json['faultcode'], 'Server') + self.assertEquals(resp.status_code, 401) diff --git a/wsmeext/cornice.py b/wsmeext/cornice.py index 0908189..c8d3568 100644 --- a/wsmeext/cornice.py +++ b/wsmeext/cornice.py @@ -39,7 +39,9 @@ class WSMEJsonRenderer(object): response = context['request'].response response.content_type = 'application/json' if 'faultcode' in data: - if data['faultcode'] == 'Client': + if 'orig_code' in data: + response.status_code = data['orig_code'] + elif data['faultcode'] == 'Client': response.status_code = 400 else: response.status_code = 500 @@ -125,7 +127,16 @@ def signature(*args, **kwargs): 'result': result } except: - return wsme.api.format_exception(sys.exc_info()) + try: + exception_info = sys.exc_info() + orig_exception = exception_info[1] + orig_code = getattr(orig_exception, 'code', None) + data = wsme.api.format_exception(exception_info) + if orig_code is not None: + data['orig_code'] = orig_code + return data + finally: + del exception_info callfunction.wsme_func = f return callfunction