如何在Exception中传递status_code,error_message

时间:2014-11-23 17:12:13

标签: python exception

我使用以下例外:

class MyApplicationPaymentError(Exception):
    pass

但是,我希望能够将status_code和error_message传递给它。所以我可以做到以下几点:

try:
    payment.validate()
except MyApplicationPaymentError:
    print '!!!', status_code, error_message

如何修改Exception,然后修改View代码以完成上述操作?

1 个答案:

答案 0 :(得分:5)

>>> class MyApplicationPaymentError(Exception):
...   def __init__(self, statuscode, errormessage):
...     self.statuscode = statuscode
...     self.errormessage = errormessage
... 
>>> try:
...   raise MyApplicationPaymentError(418, "I'm a Teapot")
... except MyApplicationPaymentError as e:
...   print(e.statuscode, e.errormessage)
... 
418 I'm a Teapot