2012-10-25 2 views
2

웹 서버를 통해 RPC 호출을위한 디스패처 작업을하고 있습니다. 웹 서버 클래스에는 rpc_echo, rpc_add, ... (rpc_ 접두어가 붙은)와 같은 몇 가지 메소드가 있으며 원격에서 액세스 할 수 있어야합니다. 디스패처 방법에서 나는 대응 방법을 찾을 수 있으며, 사전에 준비된 인수와 함께 호출이 제대로 작동파이썬 예외 소스, 디스패처

try: 
    handler = getattr(self, 'rpc_' + request['method']) # identify handler 
    response['result'] = handler(**params) # assign arguments and call handler 
except (AttributeError, KeyError): 
    # exceptions: requested method -> key, call method -> attr, callable -> attr 
    raise JSONRPCError('unknown method.') 
except TypeError: 
    raise JSONRPCError('parameters don\'t match method prototype.') 

:하지만 핸들러 내에서 예외가 발생되는 경우 오류 검사를 방해하고 리드한다 잘못된 결론으로. 예외가 처리기 내부에 던져 졌는지 아닌지 어떻게 알 수 있습니까? 따라서 잘못된 호출이나 서버 오류가 발생 했습니까?

답변

2

을 당신은 아마 여기 traceback module

함께 시간을 보내고 싶어하는 것은 간단한 예입니다 :

import sys, traceback 

def outer(b): 
    def inner(b): 
     return [0,2,99][b] 
    return "abcd"[inner(b)] 

# "abcd"[[0,2,99][1]] => "abcd"[2] => "c" 
print(outer(1)) 

try: 
    # "abcd"[[0,2,99][2]] => "abcd"[99] => IndexError 
    print(outer(2)) 
except IndexError: 
    fname = traceback.extract_tb(sys.exc_info()[2])[-1][2] 
    print("Exception from: {}".format(fname)) 

try: 
    # "abcd"[[0,2,99][3]] => IndexError 
    print(outer(3)) 
except IndexError: 
    fname = traceback.extract_tb(sys.exc_info()[2])[-1][2] 
    print("Exception from: {}".format(fname)) 

출력 :

c 
Exception from: outer 
Exception from: inner 
0

그냥/except 블록하려고 그에서 당신의 핸들러 호출을하고 다른 하나에 넣어 :

try: 
    handler = getattr(self, 'rpc_' + request['method']) # identify handler  
except (AttributeError, KeyError): 
    # exceptions: requested method -> key, call method -> attr, callable -> attr 
    raise JSONRPCError('unknown method.') 
except TypeError: 
    raise JSONRPCError('parameters don\'t match method prototype.') 

try: 
    response['result'] = handler(**params) # assign arguments and call handler 
except Exception: 
    handle_exceptions 
+0

그러나 매개 변수의 처리기 매개 변수에 대한 할당도 실패 할 수 있습니다. – Knut