rpc异常
rpc_exceptions的Python项目详细描述
跨JSON-RPC服务的简单、透明、名称间隔的异常。
安装
从pip
安装v0.1sudo pip install rpc_exceptions==0.1
从源安装v0.1
curl https://github.com/axialmarket/rpc_exceptions/achive/version_0.1.tar.gz | tar vzxf - cd rpc_exceptions sudo python setup.py install
示例
用api_名称定义一个基异常,该api的异常,并用这些异常实例化RPCExceptionHandler:
from rpc_exceptions import RPCExceptionHandler, WrappedRPCError class TestError(WrappedRPCError): api_name = 'test' class PEBCAKError(TestError): code = -1 _default_message = 'Problem exists between chair and keyboard' class FUBARError(TestError): code = -2 _default_message = 'FUBARed' error_handler = RPCExceptionHandler([ PEBCAKError, FUBARError ])
用实例化的rpcexceptionhandler的wrap_rpc_exception decorator装饰公开的函数:
from wrapped_rpc.exceptions import error_handler, PEBCAKError, FUBARError @error_handler.wrap_rpc_exception def fail1(arg): raise PEBCAKError @error_handler.wrap_rpc_exception def fail2(arg): raise FUBARError
将错误代码和消息强制为异常实例化的RPCExceptionHandler的get_exception_实例方法:
#client using tinyrpc from wrapped_rpc.exceptions import error_handler, PEBCAKError, FUBARError from tinyrpc import RPCClient, RPCError from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc.transports.http import HttpPostClientTransport class WrappedRPCClient(RPCClient): def __init__(self, protocol, transport, api_name): self.protocol = protocol self.transport = transport self.api_name = api_name def _send_and_handle_reply(self, req): reply = self.transport.send_message(req.serialize()) response = self.protocol.parse_reply(reply) if hasattr(response, 'error'): try: raise error_handler.get_exception_instance( response._jsonrpc_error_code, self.api_name, response.error) except KeyError: raise RPCError('Error calling remote procedure: %s' %\ response.error) return response rpc_client = WrappedRPCClient( JSONRPCProtocol(), HttpPostClientTransport('http://localhost:1234'), 'test' ) server = rpc_client.get_proxy() try: server.fail1('foo') except PEBCAKError as e: print 'code: %s, message: %s' % (e.code, e.msg) try: server.fail2('bar') except FUBARError as e: print 'code: %s, message: %s' % (e.code, e.msg)
许可证
bsd,请参见LICENSE.txt