decorators.py 文件源码

python
阅读 96 收藏 0 点赞 0 评论 0

项目:two1-python 作者: 21dotco 项目源码 文件源码
def catch_all(func):
    """
    Catch (nearly) all exceptions unless in debug mode.

    Args:
        func (function): function being decorated
    """
    def _catch_all(ctx, *args, **kwargs):
        """
        Args:
            ctx (click.Context): cli context object
            args (tuple): tuple of args of the fuction
            kwargs (dict): keyword args of the function
        """
        def stderr(msg):
            click.echo(click.style(msg, fg='red'), file=sys.stderr)
        try:
            return func(ctx, *args, **kwargs)
        except click.Abort:
            # on SIGINT click.prompt raises click.Abort
            logger.error('')  # just to get a newline

        except click.ClickException:
            raise  # Let click deal with it

        except Exception:
            # generic error string
            stderr(
                'You have experienced a client-side technical error.')

            # only dump the stack traces if the debug flag is set
            if kwargs.get('debug') or ctx.obj['debug']:
                stderr("\nFunction: {}.{}".format(func.__module__, func.__name__))
                stderr("Args: {}".format(args))
                stderr("Kwargs: {}".format(kwargs))
                stderr("{}".format(traceback.format_exc()))
            else:
                stderr(
                    'For more detail, run your command with the debug flag: '
                    '`21 --debug <command>.`')
        sys.exit(1)

    return functools.update_wrapper(_catch_all, func)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号