gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:37:14 26 4
gpt4 key购买 nike

我正在尝试使用库 simple_salesforce 查询 Salesforce 中的对象。如果查询无效,我会收到一个 traceback 错误,我可以使用 try, except 语句将其隔离。在此示例中,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."}]

期望的输出:

\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_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)

最佳答案

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

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)

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

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

附注在解决这个问题时,我还在 github 上遇到了这个问题:exception_handler provides inconsistent API #215

关于python - 从 Salesforce API 中隔离错误处理中的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com