我想检查我的python应用程序中的类型错误。以下列方式捕捉ValueError
是正确的方法吗?
async def find_video_by_id(request):
try:
id = int(request.query['id'])
...
except ValueError:
exception_message = "Incorrect type of video id was specified."
logger.exception(exception_message)
raven_client.captureException(exception_message)
raise ValueError(exception_message)
except Exception as ex:
logger.exception("find_video_by_id")
raven_client.captureException()
raise ex
如果你想有自定义和标准的例外,你可以执行以下操作:
# Custom Exception
class MyError(Exception):
pass
try:
id = int(request.query['id']) #raise ValueError automatically if string cannot be parsed
if id == 'foo': # just to show how to raise a custom Exception
raise MyError
else:
bar()
except ValueError:
exception_message = "Incorrect type of video id was specified."
logger.exception(exception_message)
raven_client.captureException(exception_message)
except MyError:
exception_message = "Incorrect stuff."
logger.exception(exception_message)
raven_client.captureException(exception_message)