Python 从Salesforce API隔离错误处理中的错误消息

Python 从Salesforce API隔离错误处理中的错误消息,python,python-2.7,exception,error-handling,salesforce,Python,Python 2.7,Exception,Error Handling,Salesforce,我正在尝试使用库simple\u Salesforce查询Salesforce中的对象。如果查询无效,我会得到一个traceback错误,我可以通过try(除了语句)将其隔离。在本例中,Contactd不是要查询的实际表。我真的很想隔离错误消息本身,但是e是一个类实例,所以我不确定如何隔离 我的代码: from simple_salesforce import Salesforce sf = Salesforce(username='', password=''

我正在尝试使用库
simple\u Salesforce
查询
Salesforce
中的对象。如果查询无效,我会得到一个
traceback
错误,我可以通过
try(除了
语句)将其隔离。在本例中,Contactd不是要查询的实际表。我真的很想隔离错误消息本身,但是e是一个类实例,所以我不确定如何隔离

我的代码:

from simple_salesforce import Salesforce

sf = Salesforce(username='',
                password='',
                security_token='',
                sandbox='')

try:

    print sf.query_all("SELECT Id FROM Contactd")
except Exception as e:
    print type(e)
    print e
输出:

<class 'simple_salesforce.api.SalesforceMalformedRequest'>
Malformed request https://cs42.salesforce.com/services/data/v29.0/query/?q=SELECT+Id+FROM+Contactd. Response content: [{u'errorCode': u'INVALID_TYPE', u'message': u"\nSELECT Id FROM Contactd\n               ^\nERROR at Row:1:Column:16\nsObject type 'Contactd' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names."}]
还包括
simple\u salesforce
错误处理代码:

def _exception_handler(result, name=""):
    """Exception router. Determines which error to raise for bad results"""
    try:
        response_content = result.json()
    except Exception:
        response_content = result.text

    exc_map = {
        300: SalesforceMoreThanOneRecord,
        400: SalesforceMalformedRequest,
        401: SalesforceExpiredSession,
        403: SalesforceRefusedRequest,
        404: SalesforceResourceNotFound,
    }
    exc_cls = exc_map.get(result.status_code, SalesforceGeneralError)

    raise exc_cls(result.url, result.status_code, name, response_content)

API调用返回错误数据,客户端应用程序可以使用这些数据来识别和解决运行时错误。如果在调用大多数API调用期间发生错误,则API提供以下类型的错误处理:

对于由格式错误的消息、身份验证失败或类似问题导致的错误,API将返回一条包含相关异常代码的SOAP错误消息。 对于大多数调用,如果由于特定于查询的问题而发生错误,API将返回错误。例如,如果create()请求包含200多个对象

当您通过login()调用登录时,新的客户端会话开始,并生成相应的唯一会话ID。会话在预定的不活动时间后自动过期,可通过单击安全控制在Salesforce中的设置进行配置。默认值为120分钟(两小时)。如果进行API调用,则不活动计时器将重置为零


会话过期时,将返回异常代码INVALID\u session\u ID。如果发生这种情况,您必须再次调用login()调用。

要“隔离错误消息本身”并获得所需的输出,我们可以导入
SalesforceMalformedRequest
,然后像这样使用
e.content
(在Python 3.5中)

。。。从中我们可以看到类型是
'list'
,列表包含一个
dict
;因此,为了获得所需的字符串,我们可以使用:

print(e.content[0]['message'])

p、 在解决这个问题的过程中,我在github上也遇到了这个问题:

谢谢你的解释。我想我已经到了识别第二段中提到的错误的地步,但只需要隔离其中的一部分。
from simple_salesforce import Salesforce
from simple_salesforce.exceptions import SalesforceMalformedRequest

sf = Salesforce(...)

try:
    print(sf.query_all("SELECT Id FROM Contactd"))
except SalesforceMalformedRequest as e:
    print(type(e.content))
    print(e.content)
print(e.content[0]['message'])