Add improved support for HTTP response codes in cornice apps.

Change-Id: I35efe85794e761877edd06722952292a3cac5d85
This commit is contained in:
Ryan Petrello 2013-09-06 18:02:49 -04:00
parent 0aba00b1ef
commit 62725bb773
2 changed files with 33 additions and 2 deletions

View File

@ -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)

View File

@ -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