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

How can I organize my code so that repeating try except clauses only exist once?

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)