Search code examples
pythontry-catchexcept

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


The code in the try statement is going to be different, but the try except statement itself is always the same. How can I make this less redundant?

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)

Solution

  • You can write a decorator:

    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
    

    And then use it:

    @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)