Merge "Convert api internal TypeError to HTTPBadRequest"

This commit is contained in:
Jenkins 2015-09-09 10:40:15 +00:00 committed by Gerrit Code Review
commit 89403ed23f
2 changed files with 42 additions and 1 deletions

View File

@ -339,6 +339,34 @@ class Request(webob.Request):
return content_type
class ResourceExceptionHandler(object):
"""Context manager to handle Resource exceptions.
Used when processing exceptions generated by API implementation
methods. Converts most exceptions to webob exceptions, with the
appropriate logging.
"""
def __enter__(self):
return None
def __exit__(self, ex_type, ex_value, ex_traceback):
if not ex_value:
return True
# TODO(lin.a.yang): current only handle TypeError here, we should
# process other kind of internal exceptions generated by API and
# convert to webob exceptions.
if isinstance(ex_value, TypeError):
exc_info = (ex_type, ex_value, ex_traceback)
LOG.error(_("Exception handling resource: {0}").format(ex_value),
exc_info=exc_info)
raise webob.exc.HTTPBadRequest()
# We didn't handle this kind of exception
return False
class Resource(object):
"""WSGI app that handles (de)serialization and controller dispatch.
@ -381,7 +409,9 @@ class Resource(object):
msg = _("Malformed request body")
return webob.exc.HTTPBadRequest(explanation=msg)
action_result = self.execute_action(action, request, **action_args)
with ResourceExceptionHandler():
action_result = self.execute_action(action, request, **action_args)
try:
return self.serialize_response(action, action_result, accept)
# return unserializable result (typically a webob exc)

View File

@ -191,6 +191,17 @@ class TestEnvironmentApi(tb.ControllerTest, tb.MuranoApiTestCase):
self.assertIn('Environment name should be 255 characters maximum',
result_msg)
def test_create_environment_with_empty_body(self):
"""Check that empty request body results in an HTTPBadResquest."""
body = ''
req = self._post('/environments', body)
result = req.get_response(self.api)
self.assertEqual(400, result.status_code)
result_msg = result.text.replace('\n', '')
self.assertIn('The server could not comply with the request since it '
'is either malformed or otherwise incorrect.',
result_msg)
def test_missing_environment(self):
"""Check that a missing environment results in an HTTPNotFound.