def raise_error(self, exc, identity=None):
if isinstance(exc, ApiUnauthorized):
six.reraise(
InvalidIdentity,
InvalidIdentity(self.message_from_error(exc), identity=identity),
sys.exc_info()[2]
)
elif isinstance(exc, ApiError):
six.reraise(
PluginError,
PluginError(self.message_from_error(exc)),
sys.exc_info()[2]
)
elif isinstance(exc, PluginError):
raise
else:
self.logger.exception(six.text_type(exc))
six.reraise(
PluginError,
PluginError(self.message_from_error(exc)),
sys.exc_info()[2]
)
python类reraise()的实例源码
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def decrypt(self):
"""Decrypt decrypts the secret and returns the plaintext.
Calling decrypt() may incur side effects such as a call to a remote service for decryption.
"""
if not self._crypter:
return b''
try:
plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params)
return plaintext
except Exception as e:
exc_info = sys.exc_info()
six.reraise(
ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)),
None,
exc_info[2]
)
def render(self):
"""Renders the tab to HTML using the
:meth:`~horizon.tabs.Tab.get_context_data` method and
the :meth:`~horizon.tabs.Tab.get_template_name` method.
If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load``
is not ``True``, or
either :meth:`~horizon.tabs.Tab.allowed` or
:meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will
return an empty string.
"""
if not self.load:
return ''
try:
context = self.data
except exceptions.Http302:
raise
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback)
return render_to_string(self.get_template_name(self.request), context)
def get_rows(self):
"""Return the row data for this table broken out by columns."""
rows = []
try:
for datum in self.filtered_data:
row = self._meta.row_class(self, datum)
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 __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
exc_info = sys.exc_info()
LOG.exception('Exception in string format operation')
for name, value in six.iteritems(kwargs):
LOG.error("%s: %s" % (name, value))
six.reraise(*exc_info)
self.message = message
super(WeiboError, self).__init__(message)
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
exc_info = sys.exc_info()
LOG.exception('Exception in string format operation')
for name, value in six.iteritems(kwargs):
LOG.error("%s: %s" % (name, value))
six.reraise(*exc_info)
self.message = message
super(LoginserverError, self).__init__(message)
def docker_client():
client_kwargs = dict()
if not CONF.docker.api_insecure:
client_kwargs['ca_cert'] = CONF.docker.ca_file
client_kwargs['client_key'] = CONF.docker.key_file
client_kwargs['client_cert'] = CONF.docker.cert_file
try:
yield DockerHTTPClient(
CONF.docker.api_url,
CONF.docker.docker_remote_api_version,
CONF.docker.default_timeout,
**client_kwargs
)
except errors.APIError as e:
desired_exc = exception.DockerError(error_msg=six.text_type(e))
six.reraise(type(desired_exc), desired_exc, sys.exc_info()[2])
def __call__(self, ex):
"""Re-raise any exception value not being filtered out.
If the exception was the last to be raised, it will be re-raised with
its original traceback.
"""
exc_type, exc_val, traceback = sys.exc_info()
try:
if not self._should_ignore_ex(ex):
if exc_val is ex:
six.reraise(exc_type, exc_val, traceback)
else:
raise ex
finally:
del exc_type, exc_val, traceback
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def raise_for_status(self, allow_redirects=True):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""
if self.status_code == 304:
return
elif self.error:
if self.traceback:
six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
http_error = HTTPError(self.error)
elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
http_error = HTTPError('%s Redirection' % (self.status_code))
elif (self.status_code >= 400) and (self.status_code < 500):
http_error = HTTPError('%s Client Error' % (self.status_code))
elif (self.status_code >= 500) and (self.status_code < 600):
http_error = HTTPError('%s Server Error' % (self.status_code))
else:
return
http_error.response = self
raise http_error
def setUpClass(cls):
# It should never be overridden by descendants
if hasattr(super(BaseTestCase, cls), 'setUpClass'):
super(BaseTestCase, cls).setUpClass()
cls.setUpClassCalled = True
# Stack of (name, callable) to be invoked in reverse order at teardown
cls.teardowns = []
try:
# Shortcuts to clients
cls.setup_clients()
cls.resource_setup()
except Exception:
etype, value, trace = sys.exc_info()
LOG.info("%s raised in %s.setUpClass. Invoking tearDownClass." % (
etype, cls.__name__))
cls.tearDownClass()
try:
six.reraise(etype, value, trace)
finally:
del trace # to avoid circular refs
def run_callbacks(self):
for f in self.fields:
keys = self.frb.keys()
for name, (args, kwargs) in self._callbacks:
cbw = CallbackWrapper(self, self.plots[f], self.frb, f,
self._font_properties, self._font_color)
CallbackMaker = callback_registry[name]
callback = CallbackMaker(*args[1:], **kwargs)
try:
callback(cbw)
except YTDataTypeUnsupported as e:
six.reraise(YTDataTypeUnsupported, e)
except Exception as e:
six.reraise(YTPlotCallbackError,
YTPlotCallbackError(callback._type_name, e),
sys.exc_info()[2])
for key in self.frb.keys():
if key not in keys:
del self.frb[key]
def byte_END_FINALLY(self):
v = self.pop()
if isinstance(v, str):
why = v
if why in ('return', 'continue'):
self.return_value = self.pop()
if why == 'silenced': # PY3
block = self.pop_block()
assert block.type == 'except-handler'
self.unwind_block(block)
why = None
elif v is None:
why = None
elif issubclass(v, BaseException):
exctype = v
val = self.pop()
tb = self.pop()
self.last_exception = (exctype, val, tb)
why = 'reraise'
else: # pragma: no cover
raise VirtualMachineError("Confused END_FINALLY")
return why
def from_except(cls, name, tb, exception, error_html_getter=None, error_html_getter_params={}, **data):
try:
from celery.exceptions import Retry
except ImportError:
pass
else:
if isinstance(exception, Retry):
six.reraise(Retry, exception, tb)
tb_stacks = traceback.extract_tb(tb)
stack_list = [
(cls._normalize_file_python(src_path), lineno, func_name, src_code)
for src_path, lineno, func_name, src_code in tb_stacks
]
error_html_getter = error_html_getter or (lambda exc_type, exc_value, tb, **kwargs: Reporter(exc_type, exc_value, tb).get_traceback_html())
data[cls.name_property] = name
res = cls(
stack_hash=cls._get_stack_hash(stack_list),
error_type=cls._get_except_cls_name(type(exception)),
error_html=error_html_getter(exc_type=type(exception), exc_value=exception, tb=tb, **error_html_getter_params),
**data
)
res.stack_list = stack_list
res.error_args = [repr(arg) for arg in exception.args]
return res
def _scan(self, fs, dir_path, namespaces):
"""Get an iterator of `Info` objects for a directory path.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a directory on the filesystem.
namespaces (list): A list of additional namespaces to
include in the `Info` objects.
Returns:
~collections.Iterator: iterator of `Info` objects for
resources within the given path.
"""
try:
for info in fs.scandir(dir_path, namespaces=namespaces):
yield info
except FSError as error:
if not self.on_error(dir_path, error):
six.reraise(type(error), error)
def __exit__(self, exc_type, exc_value, traceback):
ssh_errors = (
self.DIR_ERRORS
if self._directory
else self.FILE_ERRORS
)
if exc_type and isinstance(exc_value, EnvironmentError):
_errno = exc_value.errno
fserror = ssh_errors.get(_errno, errors.OperationFailed)
if _errno == errno.EACCES and sys.platform == "win32":
if getattr(exc_value, 'args', None) == 32: # pragma: no cover
fserror = errors.ResourceLocked
six.reraise(
fserror,
fserror(
self._path,
exc=exc_value
),
traceback
)
# Stops linter complaining about invalid class name
def _put_s3_object(key, body):
'''
Put an object in S3.
'''
s3_client = boto3.client('s3')
try:
response = s3_client.put_object(
Body=body,
Bucket=TS_AWS_S3_BUCKET,
Key=key
)
except ClientError as e:
exc_info = sys.exc_info()
if sys.version_info >= (3,0,0):
raise S3ClientError(e).with_traceback(exc_info[2])
else:
six.reraise(S3ClientError, S3ClientError(e), exc_info[2])
except RequestException as e:
exc_info = sys.exc_info()
if sys.version_info >= (3,0,0):
raise S3ClientError('Failure to communicate with S3').with_traceback(exc_info[2])
else:
six.reraise(S3ClientError, S3ClientError('Failure to communicate with S3'), exc_info[2])
return response
def is_available():
'''
Check ability to access S3 bucket.
'''
s3_client = boto3.client('s3')
try:
kwargs = {'Bucket': TS_AWS_S3_BUCKET}
if TS_AWS_S3_PREFIX:
kwargs['Prefix'] = TS_AWS_S3_PREFIX
s3_client.list_objects(**kwargs)
except ClientError as e:
exc_info = sys.exc_info()
if sys.version_info >= (3,0,0):
raise S3ClientError(e).with_traceback(exc_info[2])
else:
six.reraise(S3ClientError, S3ClientError(e), exc_info[2])
except RequestException as e:
exc_info = sys.exc_info()
if sys.version_info >= (3,0,0):
raise S3ClientError('Failure to communicate with S3').with_traceback(exc_info[2])
else:
six.reraise(S3ClientError, S3ClientError('Failure to communicate with S3'), exc_info[2])
return True
def close(self):
"""Closes event log reader if open.
If the i/o thread is running, this method blocks until it has been
shut down.
Further reads are not permitted after this method is called.
Raises:
Exception: To propagate any exceptions that may have been thrown
by the close operation in the other thread. If an exception
is thrown, then all subsequent calls to this method will
rethrow that same exception.
"""
with self._lock:
if not self._is_closed:
self._is_closed = True
if not self._thread.is_alive():
self._reader = None
return
self._wake_up_producer.notify()
while self._reader is not None:
self._wake_up_consumers.wait()
if self._close_exception is not None:
six.reraise(*self._close_exception)
def close_all(resources):
"""Safely closes multiple resources.
The close method on all resources is guaranteed to be called. If
multiple close methods throw exceptions, then the first will be
raised and the rest will be logged.
Args:
resources: An iterable of object instances whose classes implement
the close method.
Raises:
Exception: To rethrow the last exception raised by a close method.
"""
exc_info = None
for resource in resources:
try:
resource.close()
except Exception as e: # pylint: disable=broad-except
if exc_info is not None:
tf.logging.error('Suppressing close(%s) failure: %s', resource, e,
exc_info=exc_info)
exc_info = sys.exc_info()
if exc_info is not None:
six.reraise(*exc_info)
def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function])
try:
return state[function]
except KeyError:
try:
state[function] = result = function(*args, **kwargs)
return result
except Exception:
errors[function] = sys.exc_info()
raise
return _wrapper
def less_shitty_error_messages(func):
"""
Wraps functions where the first param is a SQL statement and enforces
any exceptions thrown will also contain the statement in the message.
"""
@wraps(func)
def inner(self, sql, *args, **kwargs):
try:
return func(self, sql, *args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
msg = '{}\nSQL: {}'.format(
e.message,
sql,
)
six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])
return inner
def get_multi(self, id_list):
# shortcut for just one id since this is a common
# case for us from EventManager.bind_nodes
if len(id_list) == 1:
id = id_list[0]
return {id: self.get(id)}
rv = self.conn.multiget(self.bucket, id_list, r=1)
results = {}
for key, value in rv.iteritems():
if isinstance(value, Exception):
six.reraise(type(value), value)
if value.status != 200:
results[key] = None
else:
results[key] = json.loads(value.data)
return results
def reraise_as(new_exception_or_type):
"""
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py
>>> try:
>>> do_something_crazy()
>>> except Exception:
>>> reraise_as(UnhandledException)
"""
__traceback_hide__ = True # NOQA
e_type, e_value, e_traceback = sys.exc_info()
if inspect.isclass(new_exception_or_type):
new_type = new_exception_or_type
new_exception = new_exception_or_type()
else:
new_type = type(new_exception_or_type)
new_exception = new_exception_or_type
new_exception.__cause__ = e_value
try:
six.reraise(new_type, new_exception, e_traceback)
finally:
del e_traceback
def stop(self):
"""Wait for the worker threads to process all items in queue.
This method blocks until there is no more work left.
It is essential to call this method. If you do any work in between
``start`` and ``stop``, make sure the ``stop`` method will always be
called, otherwise the program will never exit.
"""
for i in self.threads:
i.running = False
for i in self.threads:
i.join()
if self.exceptions:
exc_info = self.exceptions[0]
six.reraise(exc_info[0], exc_info[1], exc_info[2])
neutron_driver.py 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def create_security_group(self, context, name, description):
neutron = neutronapi.get_client(context)
body = self._make_neutron_security_group_dict(name, description)
try:
security_group = neutron.create_security_group(
body).get('security_group')
except n_exc.BadRequest as e:
raise exception.Invalid(six.text_type(e))
except n_exc.NeutronClientException as e:
exc_info = sys.exc_info()
LOG.exception(_LE("Neutron Error creating security group %s"),
name)
if e.status_code == 401:
# TODO(arosen) Cannot raise generic response from neutron here
# as this error code could be related to bad input or over
# quota
raise exc.HTTPBadRequest()
elif e.status_code == 409:
self.raise_over_quota(six.text_type(e))
six.reraise(*exc_info)
return self._convert_to_nova_security_group_format(security_group)
neutron_driver.py 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def update_security_group(self, context, security_group,
name, description):
neutron = neutronapi.get_client(context)
body = self._make_neutron_security_group_dict(name, description)
try:
security_group = neutron.update_security_group(
security_group['id'], body).get('security_group')
except n_exc.NeutronClientException as e:
exc_info = sys.exc_info()
LOG.exception(_LE("Neutron Error updating security group %s"),
name)
if e.status_code == 401:
# TODO(arosen) Cannot raise generic response from neutron here
# as this error code could be related to bad input or over
# quota
raise exc.HTTPBadRequest()
six.reraise(*exc_info)
return self._convert_to_nova_security_group_format(security_group)