def handle_cli_exceptions(exclist):
"""Decorator that will handle exceptions and output friendly messages."""
def wrap(f):
"""Returns decorator that wraps/handles exceptions."""
exclist_copy = copy.copy(exclist)
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
"""Wrapped function."""
if not exclist_copy:
f(*args, **kwargs)
else:
exc, handler = exclist_copy.pop(0)
try:
wrapped_f(*args, **kwargs)
except exc as err:
if handler is None:
raise click.UsageError(
err.response['Error']['Message']
)
elif isinstance(handler, str):
click.echo(err, err=True)
sys.exit(EXIT_CODE_DEFAULT)
@functools.wraps(f)
def _handle_any(*args, **kwargs):
"""Default exception handler."""
try:
return wrapped_f(*args, **kwargs)
except Exception as unhandled: # pylint: disable=W0703
with tempfile.NamedTemporaryFile(delete=False, mode='w') as f:
traceback.print_exc(file=f)
click.echo('Error: %s [ %s ]' % (unhandled, f.name),
err=True)
sys.exit(EXIT_CODE_DEFAULT)
return _handle_any
return wrap
评论列表
文章目录