简体   繁体   中英

how to handle fault exception in python while using zeep library to handle SOAP communications

I am trying to catch the FaultException while using zeep library for SOAP Communications.

I am able to do this when zeep librabry receives xml from client and internally parse and returns dictionary by default. While parsing the response which contains the FaultException i get below error.

As expected

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

But when i enabled raw_response = True in the Client settings, the zeep library wont parse the xml, instead just returns xml response. Now if the response contains FaultException, i am not able to catch FaultExceptions as i could not figure out how to raise FaultException from the response. Here is the response below.

<?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>

I would like to differentiate FaultExceptions and Blind Exceptions.

From docs :

For example to let zeep return the raw response directly instead of processing ...

...

# response is now a regular requests.Response object

So if you want lib to skip processing of response, you should do it manually. It means that you need to parse error message from xml and raise error manually (if you want to handle exception, of course)

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)

PS I haven't check code "in action", could be some mistakes.

in zeep you have to raise a custom exception manually and pare a message in xml.

for example

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

replace ERROR_NAME with your error type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM