Merge "Remove redundant exceptions code"

This commit is contained in:
Jenkins 2016-05-30 23:20:12 +00:00 committed by Gerrit Code Review
commit 4c77e7c729
2 changed files with 0 additions and 186 deletions

View File

@ -21,17 +21,12 @@ Includes decorator for re-raising Magnum-type exceptions.
import functools
import json
import sys
import uuid
from keystoneclient import exceptions as keystone_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
import pecan
import six
import wsme
from magnum.common import safe_utils
from magnum.i18n import _
from magnum.i18n import _LE
@ -55,113 +50,6 @@ except cfg.NoSuchOptError as e:
group='oslo_versionedobjects')
def wrap_exception(notifier=None, event_type=None):
"""This decorator wraps a method to catch any exceptions.
It logs the exception as well as optionally sending
it to the notification system.
"""
def inner(f):
def wrapped(self, context, *args, **kw):
# Don't store self or context in the payload, it now seems to
# contain confidential information.
try:
return f(self, context, *args, **kw)
except Exception as e:
with excutils.save_and_reraise_exception():
if notifier:
call_dict = safe_utils.getcallargs(f, context,
*args, **kw)
payload = dict(exception=e,
private=dict(args=call_dict)
)
temp_type = event_type
if not temp_type:
# If f has multiple decorators, they must use
# functools.wraps to ensure the name is
# propagated.
temp_type = f.__name__
notifier.error(context, temp_type, payload)
return functools.wraps(f)(wrapped)
return inner
OBFUSCATED_MSG = _('Your request could not be handled '
'because of a problem in the server. '
'Error Correlation id is: %s')
def wrap_controller_exception(func, func_server_error, func_client_error):
"""This decorator wraps controllers methods to handle exceptions:
- if an unhandled Exception or a MagnumException with an error code >=500
is catched, raise a http 5xx ClientSideError and correlates it with a log
message
- if a MagnumException is catched and its error code is <500, raise a http
4xx and logs the excp in debug mode
"""
@functools.wraps(func)
def wrapped(*args, **kw):
try:
return func(*args, **kw)
except Exception as excp:
if isinstance(excp, MagnumException):
http_error_code = excp.code
else:
http_error_code = 500
if http_error_code >= 500:
# log the error message with its associated
# correlation id
log_correlation_id = str(uuid.uuid4())
LOG.error(_LE("%(correlation_id)s:%(excp)s") %
{'correlation_id': log_correlation_id,
'excp': str(excp)})
# raise a client error with an obfuscated message
func_server_error(log_correlation_id, http_error_code)
else:
# raise a client error the original message
LOG.debug(excp)
func_client_error(excp, http_error_code)
return wrapped
def wrap_wsme_controller_exception(func):
"""This decorator wraps wsme controllers to handle exceptions."""
def _func_server_error(log_correlation_id, status_code):
raise wsme.exc.ClientSideError(
six.text_type(OBFUSCATED_MSG % log_correlation_id), status_code)
def _func_client_error(excp, status_code):
raise wsme.exc.ClientSideError(six.text_type(excp), status_code)
return wrap_controller_exception(func,
_func_server_error,
_func_client_error)
def wrap_pecan_controller_exception(func):
"""This decorator wraps pecan controllers to handle exceptions."""
def _func_server_error(log_correlation_id, status_code):
pecan.response.status = status_code
pecan.response.text = six.text_type(OBFUSCATED_MSG %
log_correlation_id)
def _func_client_error(excp, status_code):
pecan.response.status = status_code
pecan.response.text = six.text_type(excp)
pecan.response.content_type = None
return wrap_controller_exception(func,
_func_server_error,
_func_client_error)
def wrap_keystone_exception(func):
"""Wrap keystone exceptions and throw Magnum specific exceptions."""
@functools.wraps(func)
@ -235,36 +123,15 @@ class ObjectNotFound(MagnumException):
message = _("The %(name)s %(id)s could not be found.")
class ObjectNotUnique(MagnumException):
message = _("The %(name)s already exists.")
class ResourceNotFound(ObjectNotFound):
message = _("The %(name)s resource %(id)s could not be found.")
code = 404
class ResourceExists(ObjectNotUnique):
message = _("The %(name)s resource already exists.")
code = 409
class AuthorizationFailure(MagnumException):
message = _("%(client)s connection failed. %(message)s")
class UnsupportedObjectError(MagnumException):
message = _('Unsupported object type %(objtype)s')
class IncompatibleObjectVersion(MagnumException):
message = _('Version %(objver)s of %(objname)s is not supported')
class OrphanedObjectError(MagnumException):
message = _('Cannot call %(method)s on orphaned %(objtype)s object')
class Invalid(MagnumException):
message = _("Unacceptable parameters.")
code = 400
@ -287,10 +154,6 @@ class GetDiscoveryUrlFailed(MagnumException):
message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
class InvalidUuidOrName(Invalid):
message = _("Expected a name or uuid but received %(uuid)s.")
class InvalidIdentity(Invalid):
message = _("Expected an uuid or int but received %(identity)s.")
@ -308,20 +171,12 @@ class Conflict(MagnumException):
code = 409
class InvalidState(Conflict):
message = _("Invalid resource state.")
# Cannot be templated as the error syntax varies.
# msg needs to be constructed when raised.
class InvalidParameterValue(Invalid):
message = _("%(err)s")
class InstanceNotFound(ResourceNotFound):
message = _("Instance %(instance)s could not be found.")
class PatchError(Invalid):
message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")
@ -335,13 +190,6 @@ class PolicyNotAuthorized(NotAuthorized):
message = _("Policy doesn't allow %(action)s to be performed.")
class NotAcceptable(MagnumException):
# TODO(yuntongjin): We need to set response headers
# in the API for this exception
message = _("Request not acceptable.")
code = 406
class InvalidMAC(Invalid):
message = _("Expected a MAC address but received %(mac)s.")

View File

@ -12,8 +12,6 @@
import inspect
import mock
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
@ -23,38 +21,6 @@ class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestWrapException(base.BaseTestCase):
def test_wrap_exception_good_return(self):
def good_function(self, context):
return 99
wrapped = exception.wrap_exception()
self.assertEqual(99, wrapped(good_function)(1, 2))
def test_wrap_exception_with_notifier(self):
test_exc = TestMagnumException(name="NAME")
def bad_function(self, context, extra, blah="a", boo="b", zoo=None):
raise test_exc
expected_context = 'context'
expected_event_type = 'bad_function'
expected_payload = {
'exception': test_exc, 'private': {'args': {
'self': None, 'context': expected_context, 'extra': 1,
'blah': 'a', 'boo': 'b', 'zoo': 3}}}
notifier = mock.MagicMock()
wrapped = exception.wrap_exception(notifier)
self.assertRaises(
TestMagnumException, wrapped(bad_function), None,
expected_context, 1, zoo=3)
notifier.error.assert_called_once_with(
expected_context, expected_event_type, expected_payload)
class TestException(base.BaseTestCase):
def raise_(self, ex):