def translate_cinder_exception(method):
"""Transforms a cinder exception but keeps its traceback intact."""
@functools.wraps(method)
def wrapper(self, ctx, *args, **kwargs):
try:
res = method(self, ctx, *args, **kwargs)
except (cinder_exception.ConnectionError,
keystone_exception.ConnectionError):
exc_type, exc_value, exc_trace = sys.exc_info()
exc_value = exception.CinderConnectionFailed(
reason=six.text_type(exc_value))
six.reraise(exc_value, None, exc_trace)
except (keystone_exception.BadRequest,
cinder_exception.BadRequest):
exc_type, exc_value, exc_trace = sys.exc_info()
exc_value = exception.InvalidInput(
reason=six.text_type(exc_value))
six.reraise(exc_value, None, exc_trace)
except (keystone_exception.Forbidden,
cinder_exception.Forbidden):
exc_type, exc_value, exc_trace = sys.exc_info()
exc_value = exception.Forbidden(message=six.text_type(exc_value))
six.reraise(exc_value, None, exc_trace)
return res
return wrapper
python类reraise()的实例源码
def convert_exceptions(function, exception_map):
expected_exceptions = tuple(exception_map.keys())
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except expected_exceptions as ex:
raised_exception = exception_map.get(type(ex))
if not raised_exception:
# exception might be a subclass of an expected exception.
for expected in expected_exceptions:
if isinstance(ex, expected):
raised_exception = exception_map[expected]
break
exc_info = sys.exc_info()
# NOTE(claudiub): Python 3 raises the exception object given as
# the second argument in six.reraise.
# The original message will be maintained by passing the original
# exception.
exc = raised_exception(six.text_type(exc_info[1]))
six.reraise(raised_exception, exc, exc_info[2])
return wrapper
def _handle_create_exception(*exc_info):
"""The `CREATE_EXCEPTIONS` dict containing the relationships between
the nova exceptions and the webob exception classes to be raised is
defined at the top of this file.
"""
error = exc_info[1]
err_cls = error.__class__
cls_to_raise = CREATE_EXCEPTIONS.get(err_cls)
if cls_to_raise is None:
# The error is a subclass of one of the dict keys
to_raise = [val for key, val in CREATE_EXCEPTIONS.items()
if isinstance(error, key)]
if len(to_raise) > 1:
cls_to_raise = Controller._resolve_exception(to_raise)
elif not to_raise:
# Not any of the expected exceptions, so re-raise
six.reraise(*exc_info)
else:
cls_to_raise = to_raise[0]
for key, val in CREATE_EXCEPTIONS_MSGS.items():
if isinstance(error, key):
raise cls_to_raise(explanation=CREATE_EXCEPTIONS_MSGS[key])
raise cls_to_raise(explanation=error.format_message())
def load(self):
"""Load controlled schema version info from DB"""
tname = self.repository.version_table
try:
if not hasattr(self, 'table') or self.table is None:
self.table = Table(tname, self.meta, autoload=True)
result = self.engine.execute(self.table.select(
self.table.c.repository_id == str(self.repository.id)))
data = list(result)[0]
except:
cls, exc, tb = sys.exc_info()
six.reraise(exceptions.DatabaseNotControlledError,
exceptions.DatabaseNotControlledError(str(exc)), tb)
self.version = data['version']
return data
def get(self, wrap_exception=False):
"""
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
"""
if self.has_exception:
if wrap_exception:
raise RetryError(self)
else:
six.reraise(self.value[0], self.value[1], self.value[2])
else:
return self.value
def _raise(exc):
if six.PY2 and isinstance(exc, tuple):
(exc_type, value, traceback) = exc
six.reraise(exc_type, value, traceback)
else:
raise exc
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in self.kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
for k, v in self.kwargs.items():
if isinstance(v, Exception):
self.kwargs[k] = six.text_type(v)
if self._should_format(message):
try:
message = self.message % kwargs
except Exception:
exc_info = sys.exc_info()
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation'))
for name, value in kwargs.items():
LOG.error(_LE("%(name)s: %(value)s"),
{'name': name, 'value': value})
if CONF.fatal_exception_format_errors:
six.reraise(*exc_info)
# at least get the core message out if something happened
message = self.message
elif isinstance(message, Exception):
message = six.text_type(message)
# NOTE(luisg): We put the actual message in 'msg' so that we can access
# it, because if we try to access the message via 'message' it will be
# overshadowed by the class' message attribute
self.msg = message
super(VDIBrokerException, self).__init__(message)
def get_connection(alias=DEFAULT_CONNECTION_NAME, db=None):
global _connections
global _default_dbs
if alias not in _connections:
conn_settings = _connection_settings[alias].copy()
db = conn_settings.pop('name', None)
connection_class = MotorClient
if 'replicaSet' in conn_settings:
connection_class = MotorReplicaSetClient
conn_settings['hosts_or_uri'] = conn_settings.pop('host', None)
# Discard port since it can't be used on MongoReplicaSetClient
conn_settings.pop('port', None)
# Discard replicaSet if not base string
if not isinstance(conn_settings['replicaSet'], six.string_types):
conn_settings.pop('replicaSet', None)
try:
_connections[alias] = connection_class(**conn_settings)
except Exception:
exc_info = sys.exc_info()
err = ConnectionError("Cannot connect to database %s :\n%s" % (alias, exc_info[1]))
raise six.reraise(ConnectionError, err, exc_info[2])
try:
if not _connections[alias].connected:
_connections[alias].open_sync()
except Exception:
exc_info = sys.exc_info()
err = ConnectionError("Cannot connect to database %s :\n%s" % (alias, exc_info[1]))
raise six.reraise(ConnectionError, err, exc_info[2])
database = None
if db is None:
database = getattr(_connections[alias], _default_dbs[alias])
else:
database = getattr(_connections[alias], db)
return Database(_connections[alias], database)
def get_rows(self):
"""Return the row data for this table broken out by columns.
The row objects get an additional ``form`` parameter, with the
formset form corresponding to that row.
"""
try:
rows = []
if self.formset_class is None:
formset = []
else:
formset = self.get_formset()
formset.is_valid()
for datum, form in six.moves.zip_longest(self.filtered_data,
formset):
row = self._meta.row_class(self, datum, form)
if self.get_object_id(datum) == self.current_item_id:
self.selected = True
row.classes.append('current_selected')
rows.append(row)
except Exception:
# Exceptions can be swallowed at the template level here,
# re-raising as a TemplateSyntaxError makes them visible.
LOG.exception("Error while rendering table rows.")
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
return rows
def value(self):
"""Returns a formatted version of the data for final output.
This takes into consideration the
:attr:`~horizon.tables.Column.link`` and
:attr:`~horizon.tables.Column.empty_value`
attributes.
"""
try:
data = self.column.get_data(self.datum)
if data is None:
if callable(self.column.empty_value):
data = self.column.empty_value(self.datum)
else:
data = self.column.empty_value
except Exception:
data = None
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
if self.url and not self.column.auto == "form_field":
link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in
self.column.link_attrs.items()])
# Escape the data inside while allowing our HTML to render
data = mark_safe('<a href="%s" %s>%s</a>' % (
(escape(self.url),
link_attrs,
escape(six.text_type(data)))))
return data
def _ReraiseTypeErrorWithFieldName(message_name, field_name):
"""Re-raise the currently-handled TypeError with the field name added."""
exc = sys.exc_info()[1]
if len(exc.args) == 1 and type(exc) is TypeError:
# simple TypeError; add field name to exception message
exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name))
# re-raise possibly-amended exception with original traceback:
six.reraise(type(exc), exc, sys.exc_info()[2])
def _reraise_translated_image_exception(image_id):
"""Transform the exception for the image but keep its traceback intact."""
# pylint: disable=unused-variable
_exc_type, exc_value, exc_trace = sys.exc_info()
new_exc = _translate_image_exception(image_id, exc_value)
six.reraise(type(new_exc), new_exc, exc_trace)
def _reraise_translated_exception():
"""Transform the exception but keep its traceback intact."""
# pylint: disable=unused-variable
_exc_type, exc_value, exc_trace = sys.exc_info()
new_exc = _translate_plain_exception(exc_value)
six.reraise(type(new_exc), new_exc, exc_trace)
def __get__(self, instance, owner):
# Tell the ClientManager to login to keystone
if self._handle is None:
try:
self._handle = self.factory(instance)
except AttributeError as err:
# Make sure the failure propagates. Otherwise, the plugin just
# quietly isn't there.
new_err = exceptions.PluginAttributeError(err)
six.reraise(new_err.__class__, new_err, sys.exc_info()[2])
return self._handle
def __init__(self, reraise=True, logger=None):
self.reraise = reraise
if logger is None:
logger = logging.getLogger()
self.logger = logger
self.type_, self.value, self.tb = (None, None, None)
def force_reraise(self):
if self.type_ is None and self.value is None:
raise RuntimeError("There is no (currently) captured exception"
" to force the reraising of")
six.reraise(self.type_, self.value, self.tb)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
if self.reraise:
self.logger.error(_LE('Original exception being dropped: %s'),
traceback.format_exception(self.type_,
self.value,
self.tb))
return False
if self.reraise:
self.force_reraise()
def apply_rules(*rules):
def decorator(func):
@wraps(func)
def api_rule_check_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except RQInvalidArgument:
raise
except Exception:
exc_info = sys.exc_info()
t, v, tb = exc_info
try:
call_args = inspect.getcallargs(unwrapper(func), *args, **kwargs)
except TypeError as e:
six.reraise(RQTypeError, RQTypeError(*e.args), tb)
return
try:
for r in rules:
r.verify(func.__name__, call_args[r.arg_name])
except RQInvalidArgument as e:
six.reraise(RQInvalidArgument, e, tb)
return
raise
api_rule_check_wrapper._rq_exception_checked = True
return api_rule_check_wrapper
return decorator
def load(taskName,ignoreEntities=[]):
"""
Download and load the corresponding corpus from the BioNLP Shared Task
:param taskName: The name of the shared task to download (e.g. 'BioNLP-ST-2016_BB-event_train'). Use kindred.bionlpst.listTasks() to get a list of valid options
:param ignoreEntities: A list of any entities that should be ignored during loading
:type taskName: str
:type ignoreEntities: list of str
:return: The loaded corpus
:rtype: kindred.Corpus
"""
global taskOptions
tempDir = tempfile.mkdtemp()
assert taskName in taskOptions.keys(), "%s not a valid option in %s" % (taskName, taskOptions.keys())
url,expectedFile,expectedSHA256 = taskOptions[taskName]
filesToDownload = [(url,expectedFile,expectedSHA256)]
expectedDir = expectedFile.replace('.zip','')
try:
kindred.utils._downloadFiles(filesToDownload,tempDir)
except:
exc_info = sys.exc_info()
shutil.rmtree(tempDir)
six.reraise(*exc_info)
mainDir = kindred.utils._findDir(expectedDir,tempDir)
corpus = kindred.loadDir(dataFormat='standoff',directory=mainDir,ignoreEntities=ignoreEntities)
shutil.rmtree(tempDir)
return corpus
def resume(self):
"restore and re-raise any exception"
if '_saved' not in vars(self):
return
type, exc = map(pickle.loads, self._saved)
six.reraise(type, exc, self._tb)