【问题标题】:how to handle fault exception in python while using zeep library to handle SOAP communications如何在使用 zeep 库处理 SOAP 通信时在 python 中处理错误异常
【发布时间】:2019-05-22 13:06:44
【问题描述】:

我试图在使用 zeep 库进行 SOAP 通信时捕获 FaultException。

当 zeep librabry 从客户端接收 xml 并在内部解析并默认返回字典时,我能够做到这一点。在解析包含 FaultException 的响应时,我得到以下错误。

如预期的那样

Traceback (most recent call last):
  File "zeep_test_emulator.py", line 83, in <module>
    raise zeep_exceptions.Fault(faultexe.message)
zeep.exceptions.Fault: Forename contains invalid characters

但是当我在客户端设置中启用 raw_response = True 时,zeep 库不会解析 xml,而是只返回 xml 响应。现在,如果响应包含 FaultException,我将无法捕获 FaultExceptions,因为我无法弄清楚如何从响应中引发 FaultException。以下是回复。

<?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
      <soap:Fault>
        <faultcode>soap:Client</faultcode>
        <faultstring>Forename contains invalid characters</faultstring> 
        <faultactor>https://ct.abcd.co.uk/services.asmx</faultactor> 
        <detail />
      </soap:Fault>
    </soap:Body>
  </soap:Envelope>

我想区分 FaultExceptions 和 Blind Exceptions。

【问题讨论】:

    标签: python soap zeep


    【解决方案1】:

    来自docs

    例如让 zeep 直接返回原始响应而不是处理...

    ...

    # response is now a regular requests.Response object

    因此,如果您希望 lib 跳过响应处理,则应手动执行。这意味着您需要从 xml 解析错误消息并手动引发错误(如果您想处理异常,当然)

    import xml.etree.ElementTree as ET
    from zeep.exceptions import Fault
    
    ...
    
    response = client.service.myoperation()
    
    try:
        root = ET.fromstring(response.text)
        error_text = next(root.iter("faultstring")).text
    except:
        error_text = "" 
    
    if error_text:
        raise Fault(error_text)
    

    附:我还没有检查“运行中”的代码,可能是一些错误。

    【讨论】:

      【解决方案2】:

      在 zeep 中,您必须手动引发自定义异常并在 xml 中删除消息。

      例如

      class Error(Exception):
          """Base class for other exceptions"""
          pass
      
      class ERROR_NAME(Error):
          """Raised when the ERROR_NAME"""
          pass
      
      
      try:
          zeep call code...
      
      except ERROR_NAME:
          print('STH')
      

      ERROR_NAME 替换为您的错误类型

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多