python - 我如何组织我的代码,以便重复的 try except 子句只存在一次?

标签 python try-catch except

try 语句中的代码会有所不同,但 try except 语句本身总是相同的。我怎样才能减少它的冗余?

def cloudflare_add_zone(ctx, url, jumpstart, organization):
    try:

        if organization:
            ctx.create_zone(url, jumpstart, organization)
        else:
            ctx.create_zone(url, jumpstart)
        click.echo('Zone successfully created: %s' % url)

    except HTTPServiceError, e:
        code = str(e.details['errors'][0]['code'])
        message = e.details['errors'][0]['message']
        click.echo(code + ":" + message)

def cloudflare_add_record(ctx, domain, name, type, content, ttl):
    try:

        payload = {
            'type': type,
            'name': name,
            'content': content
        }
        if ttl:
            payload['ttl'] = ttl
        zone_id = ctx.get_zone_by_name(domain).get('id')
        ctx.create_dns_record(zone_id, payload)

    except HTTPServiceError, e:
        code = str(e.details['errors'][0]['code'])
        message = e.details['errors'][0]['message']
        click.echo(code + ":" + message)

最佳答案

你可以写一个装饰器:

from functools import wraps

def http_safe(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except HTTPServiceError, e:
            click.echo('{[code]}: {[message]}'.format(e.details['errors'][0]))
   return wrapper

然后使用它:

@http_safe
def cloudflare_add_zone(ctx, url, jumpstart, organization):
    if organization:
        ctx.create_zone(url, jumpstart, organization)
    else:
        ctx.create_zone(url, jumpstart)
    click.echo('Zone successfully created: %s' % url)

关于python - 我如何组织我的代码,以便重复的 try except 子句只存在一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567928/

相关文章:

python - 简化pan​​das表达式

python - 数组与整数

Python:使用 __self__ 而不是 self 作为 "instance method"的第一个参数

python - 使用 Tensorflow Serving 服务 Keras 模型

java - java异常的catch block 中是否会捕获断言错误?

c# - List<T>.Except(List<T>) 未按预期工作

XSLT 选择除一个子节点文本之外的所有文本

c# - System.Linq.Enumerable+WhereSelectArrayIterator 与 List<T> 上的 IEnumerable.Except()

java - Try block 导致 Stream 关​​闭 IOException

php - 如何在try/catch语句laravel中记录错误?