我正在使用Twilio的API返回有关电话号码的信息。一些电话号码无效并返回错误,例如
Traceback (most recent call last):
File "test_twilio.py", line 17, in <module>
number = client.lookups.phone_numbers("(4154) 693-
6078").fetch(type="carrier")
File "/Users/jawnsano/anaconda/lib/python2.7/site-
packages/twilio/rest/lookups/v1/phone_number.py", line 158, in fetch
params=params,
File "/Users/jawnsano/anaconda/lib/python2.7/site-
packages/twilio/base/version.py", line 82, in fetch
raise self.exception(method, uri, response, 'Unable to fetch
record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
GET /PhoneNumbers/(4154) 693-6078
Twilio returned the following information:
Unable to fetch record: The requested resource /PhoneNumbers/(4154)
693-6078 was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
如果返回如上所示的错误,我想打印“有错误”。但是,对于我的if语句,是否有一种方法可以使Python打印出通常存在回溯错误/错误的情况?我认为可能有比设置使其更好的方法
if returned_value = (super long error message):
etc...
最佳答案
您可以使用try和except来捕获错误。
from twilio.base.exceptions import TwilioRestException
try:
... your code
except TwilioRestException:
print("whatever")
关于python - 如何在Python中编写可用于异常/错误的if-else语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46090079/