2012-10-25 34 views
2

我正在通過web服務器調用RPC調用的調度程序。 webserver類有一些方法,如rpc_echo,rpc_add,...(以rpc_開頭),這些方法應該可以從遠程訪問。在調度方法,我可以找到相應的方法,並在字典中準備的參數來調用它:python異常源,調度程序

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