I have the following problem: my application is a bridge between dbus and json-rpc. I have a dbus library that in case of Dbus exception is raising a
DBusException("my err msg") exception.
My json-rpc library is catching all the Exception and convert it to a nice generic server error message
{"jsonrpc": "2.0", "error": {"code": -32000, "message": "Server error"}, "id": 2}
The problem is that i want to handle better those exceptions and I can distinguish between them only using the error message: for example I need to convert the
DBusException("Invalid Parameters")
to
{"jsonrpc": "2.0", "error": {"code": -32001, "message": "Server error", data="Invalid Parameters" }, "id": 2}
that can be done raising in my library an ApiError(msg, code, data) exception.
So summarizing: - I need to catch a DBusException - based on the err_msg I need to switch between different exception types and re-raise a modified ApiError exception
How is the better approach to that? this needs to be done in at least 10 functions that have the same exceptions.
1) using a decorator?
def my_exception_catcher(fun, *args, **kwargv):
try:
fun(args, *argv)
except DBusException as e
err_msg = str(e)
if err_msg == "Invalid Arguments":
raise ApiError("Server Error", code=1, data=err_msg)
else if err_msg == "Connect Error":
raise ApiError("Server Error", code=2, data=err_msg)
else:
raise
@my_exception_catcher
my_fun(*args):
do_something
2) using a function to determine the exception type?
def find_my_dbus_error(err_msg):
if err_msg == "Invalid Arguments":
return ApiError("Server Error", code=1, data=err_msg)
else if err_msg == "Connect Error":
return ApiError("Server Error", code=2, data=err_msg)
else:
return Exception(err_msg)
try:
my_fun(params)
except DBusException as e
raise find_my_dbus_error(err_msg)
3) something else?
Thanks Nick
Aucun commentaire:
Enregistrer un commentaire