python异常源,调度程序

时间:2012-10-25 14:49:48

标签: python exception

我正在通过网络服务器处理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.')

这很好用但是如果在处理程序中抛出异常,则错误检查会受到干扰并导致错误的结论。如何判断异常是否在处理程序内抛出?因此错误的呼叫或服务器错误?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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