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

2024-04-16 11:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用库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

输出:

^{pr2}$

期望输出:

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

Tags: thetonameresponseexceptionresultcontentsimple
2条回答

为了“隔离错误消息本身”并获得所描述的所需输出,我们可以导入SalesforceMalformedRequest,然后像这样使用e.content(在Python3.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;因此,要获得所需的字符串,我们可以使用:

^{pr2}$

另外,在解决这个问题时,我在github上也遇到了这个问题:exception_handler provides inconsistent API #215

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

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

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

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

相关问题 更多 >