2

我正在开发一个通过网络服务器进行 RPC 调用的调度程序。webserver 类有一些方法,如 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.')

这工作正常:但是如果在处理程序内部抛出异常,错误检查就会受到干扰并导致错误的结论。如何确定异常是否在处理程序中引发?因此是错误的调用或服务器错误?

4

2 回答 2

2

您可能想花一些时间使用回溯模块

这是一个简化的例子:

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
于 2012-10-25T18:02:13.717 回答
0

只需将您的处理程序调用从该 try/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
于 2012-10-25T14:54:33.097 回答