2017-01-14 11 views
1

私は次のコードに10を加えたとしましょう。Python - ジェネリック関数として例外キャッチを扱う簡単な方法

try: 
    session.get('http://www.google.com') 
except rex.MissingSchema as e: 
    raise RESTClientException('Bad URL for request: ' + str(url), 'error:url', e) 
except rex.ConnectionError as e: 
    raise RESTClientException('Cannot connect for token', 'error:connection', e) 
except rfcex.InsecureTransportError as e: 
    raise RESTClientException('Verify certificates True without https', 'error:https', e) 

これらのすべてを、複数の機能で正確にはどのように使用したいとします。私がこれを行うと考えることができる唯一の方法は次のとおりです。

もっと良い方法がありますか? ありがとう

+1

なぜありません単純に自分自身の機能でtry/wrapをラップする –

答えて

1

私はデコレータを使用して、関数内で発生する可能性のある特定のタイプの例外を別の例外タイプにラップします。目標は、を除くに1つの例外タイプをクライアントコードに提供することです。 これは、主に後である場合、各機能のRESTClientExceptionをエレガントに再発生させるのに役立ちます。ただし、エラーメッセージは変換されません。

def wrap_known_exceptions(exceptions_to_wrap, exception_to_raise): 
"""Wrap a tuple of known exceptions into another exception to offer client 
code a single error to try/except against. 

Args: 
    exceptions_to_wrap (instance or tuple): Tuple of exception types that 
     are caught when arising and wrapped. 
    exception_to_raise (Exception type): Exception that will be raised on 
     an occurence of an exception from ``exceptions_to_wrap``. 

Raises: 
    exception_to_raise's type. 
""" 
def closure(func): 

    @wraps(func) 
    def wrapped_func(*args, **kwargs): 
     try: 
      return func(*args, **kwargs) 
     except exceptions_to_wrap as exception_instance: 
      msg = u"wraps {0}: {1}" 
      msg = msg.format(type(exception_instance).__name__, exception_instance) 
      raise exception_to_raise(msg) 

    return wrapped_func 
return closure 

(オリジナルのメッセージが!?十分に明らかにされていないとして、多分それは、あなたのためのより重要だった)ここではそれが使われている方法は次のとおりです。

class RESTClientException(Exception): 
    """RESTClientException""" 

@wrap_known_exceptions(ValueError, RESTClientException) # could also be a tuple 
def test(): 
    raise ValueError("Problem occured") 

test() 

出力:

Traceback (most recent call last): 
    File "C:/symlinks/..../utilities/decorators.py", line 69, in <module> 
    test() 
    File "C:/symlinks/..../utilities/decorators.py", line 32, in wrapped_func 
    raise exception_to_raise(msg) 
__main__.RESTClientException: wraps ValueError: Problem occured 
+0

優れたアイデア!私は少し簡素化し、私の特定の例外のためにそれを使用するが、デコレータは行くための素晴らしい方法です! –

関連する問題