Disect a UPnP error, and raise an appropriate exception.

        Args:
            xml_error (str):  a unicode string containing the body of the
                UPnP/SOAP Fault response. Raises an exception containing the
                error code.
541008
def handle_upnp_error(self, xml_error):
        

        # An error code looks something like this:

        # HTTP/1.1 500 Internal Server Error
        # CONTENT-LENGTH: bytes in body
        # CONTENT-TYPE: text/xml; charset="utf-8"
        # DATE: when response was generated
        # EXT:
        # SERVER: OS/version UPnP/1.0 product/version

        # <?xml version="1.0"?>
        # <s:Envelope
        #   xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
        #   s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        #   <s:Body>
        #       <s:Fault>
        #           <faultcode>s:Client</faultcode>
        #           <faultstring>UPnPError</faultstring>
        #           <detail>
        #               <UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
        #                   <errorCode>error code</errorCode>
        #                   <errorDescription>error string</errorDescription>
        #               </UPnPError>
        #           </detail>
        #       </s:Fault>
        #   </s:Body>
        # </s:Envelope>
        #
        # All that matters for our purposes is the errorCode.
        # errorDescription is not required, and Sonos does not seem to use it.

        # NB need to encode unicode strings before passing to ElementTree
        xml_error = xml_error.encode('utf-8')
        error = XML.fromstring(xml_error)
        log.debug("Error %s", xml_error)
        error_code = error.findtext(
            './/{urn:schemas-upnp-org:control-1-0}errorCode')
        if error_code is not None:
            description = self.UPNP_ERRORS.get(int(error_code), '')
            raise SoCoUPnPException(
                message='UPnP Error {} received: {} from {}'.format(
                    error_code, description, self.soco.ip_address),
                error_code=error_code,
                error_description=description,
                error_xml=xml_error
            )
        else:
            # Unknown error, so just return the entire response
            log.error("Unknown error received from %s", self.soco.ip_address)
            raise UnknownSoCoException(xml_error)
1009572
def call(self, action_name, arg_in=None, http_auth=None, http_headers=None):
        
        if arg_in is None:
            arg_in = {}

        soap_env = '{%s}' % NS_SOAP_ENV
        m = '{%s}' % self.service_type

        root = etree.Element(soap_env+'Envelope', nsmap={'SOAP-ENV': NS_SOAP_ENV})
        root.attrib[soap_env+'encodingStyle'] = ENCODING_STYLE
        body = etree.SubElement(root, soap_env+'Body')
        action = etree.SubElement(body, m+action_name, nsmap={'m': self.service_type})
        for key, value in arg_in.items():
            etree.SubElement(action, key).text = str(value)
        body = etree.tostring(root, encoding=ENCODING, xml_declaration=True)
        headers = {
            'SOAPAction': '"%s#%s"' % (self.service_type, action_name),
            'Host': self._host,
            'Content-Type': 'text/xml',
            'Content-Length': str(len(body)),
        }
        headers.update(http_headers or {})

        try:
            resp = requests.post(
                self.url,
                body,
                headers=headers,
                timeout=SOAP_TIMEOUT,
                auth=http_auth
            )
            resp.raise_for_status()
        except requests.exceptions.HTTPError as exc:
            # If the body of the error response contains XML then it should be a UPnP error,
            # otherwise reraise the HTTPError.
            try:
                err_xml = etree.fromstring(exc.response.content)
            except etree.XMLSyntaxError:
                raise exc
            raise SOAPError(*self._extract_upnperror(err_xml))

        xml_str = resp.content.strip()
        try:
            xml = etree.fromstring(xml_str)
        except etree.XMLSyntaxError:
            # Try removing any extra XML declarations in case there are more than one.
            # This sometimes happens when a device sends its own XML config files.
            xml = etree.fromstring(self._remove_extraneous_xml_declarations(xml_str))
        except ValueError:
            # This can occur when requests returns a `str` (unicode) but there's also an XML
            # declaration, which lxml doesn't like.
            xml = etree.fromstring(xml_str.encode('utf8'))

        response = xml.find(".//{%s}%sResponse" % (self.service_type, action_name))
        if response is None:
            msg = ('Returned XML did not include an element which matches namespace %r and tag name'
                   ' \'%sResponse\'.' % (self.service_type, action_name))
            self._log.debug(msg + '\n' + etree.tostring(xml, pretty_print=True).decode('utf8'))
            raise SOAPProtocolError(msg)

        # Sometimes devices return XML strings as their argument values without escaping them with
        # CDATA. This checks to see if the argument has been parsed as XML and un-parses it if so.
        ret = {}
        for arg in response.getchildren():
            children = arg.getchildren()
            if children:
                ret[arg.tag] = b"\n".join(etree.tostring(x) for x in children)
            else:
                ret[arg.tag] = arg.text

        return ret
485344
public static function readErrors($str_xml)
    {
        $parser = new PagSeguroXmlParser($str_xml);
        $data = $parser->getResult('errors');
        $errors = array();
        if (isset($data['error']) && is_array($data['error'])) {
            if (isset($data['error']['code']) && isset($data['error']['message'])) {
                array_push($errors, new PagSeguroError($data['error']['code'], $data['error']['message']));
            } else {
                foreach ($data['error'] as $key => $value) {
                    if (isset($value['code']) && isset($value['message'])) {
                        array_push($errors, new PagSeguroError($value['code'], $value['message']));
                    }
                }
            }
        }
        return $errors;
    }
1195380
def parse_error(self, exception=ParseError, *args):
        
        return self._src.parse_error(exception, *args)
946590
def _raise_error(self, status_code, raw_data):
        
        error_message = raw_data
        additional_info = None
        try:
            additional_info = json.loads(raw_data)
            error_message = additional_info.get('error', error_message)
            if isinstance(error_message, dict) and 'type' in error_message:
                error_message = error_message['type']
        except:
            pass

        raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
167494
def get_security_error(node):
        
        assert node.name() == 'securityData' and not node.isArray()
        if node.hasElement('securityError'):
            secid = XmlHelper.get_child_value(node, 'security')
            err = XmlHelper.as_security_error(node.getElement('securityError'), secid)
            return err
        else:
            return None
1092476
async def on_raw_error(self, message):
        
        error = protocol.ServerError(' '.join(message.params))
        await self.on_data_error(error)
177889
public void error(String msg, Object[] args)
  {

    System.out.println("DOM ERROR! class: " + this.getClass().getName());

    throw new RuntimeException(XMLMessages.createXMLMessage(msg, args));  //"UnImplNode error: "+msg);
  }
808812
def error(self, msg):
        """"""

        self._error = True
        self._progress.printMsg('XML parse error: %s' % msg, error=True)
877781
def _call_xml_operation(op_sym, body, extract=nil)
      @operation = _operation(op_sym)
      @operation.body = body
      @response = operation.call

      # Check for http errors?

      # Handle faults (before extracting data)
      _envelope.xpath("soap:Body/soap:Fault", namespaces).each do | fault |
        raise Exception, fault.to_s
      end
      
      # Extract data
      if extract.respond_to?(:call)
        @xml = extract.call(response)
      else
        @xml = response.raw
      end
      
      # Handle errors

      ng = Nokogiri.XML(xml)
      ng.xpath("/data/errors/error").each do | error |
        if error.key?("code")
          case error["code"].to_i
          when 4
            raise NodataException
          end
          #<error code="2">max response reached</error>
          #<error code="3">authentification error</error>
          #<error code="9">start date upper than end date</error>
        else
          raise Exception, error
        end
      end
      
      # Validation - only :getXml
      if [:getXml].include? op_sym
        # Validation against getXSD schema does not work: ["Element 'data': No matching global declaration available for the validation root."]
        # See https://github.com/npolar/argos-ruby/commit/219e4b3761e5265f8f9e8b924bcfc23607902428 for the fix
        schema = Nokogiri::XML::Schema(File.read("#{__dir__}/_xsd/argos-data.xsd"))
        v = schema.validate(ng)
        if v.any?
          log.debug "#{v.size} errors: #{v.map{|v|v.to_s}.uniq.to_json}"
        end
      end
      

      # Convert XML to Hash
      nori = Nori.new
      nori.parse(xml)
    end
1235188
def serialize_soap_fault(ex)
      logger.debug "Serializing SOAP Fault: #{ex.inspect}"

      xb = Builder::XmlMarkup.new
      xb.instruct!

      xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv|
        xenv.tag! 'e:Body' do |xbody|
          xbody.tag! 'e:Fault' do |xf|
            case soap_version
              when :soap11
                xf.faultcode "e:Server.#{ex.class.name}"
                xf.faultstring ex.message
              when :soap12
                xf.tag! 'e:Code' do |xcode|
                  xcode.tag! 'e:Value', 'e:Receiver'
                  xcode.tag! 'e:Subcode' do |xsubcode|
                    xsubcode.tag! 'e:Value', ex.class.name
                  end
                end
                xf.tag! 'e:Reason', ex.message
              else
                raise "Unsupported SOAP version: #{soap_version}"
            end
          end
        end
      end
    end
1189513
static Optional<XmlElement> getErrorElement(XmlElement rootXmlElement) {
    Optional<XmlElement> elem = rootXmlElement.getChildOpt("error");
    if (elem.isPresent()) {
      ApiException error = elem.transform(toApiException()).get();
      log.error(error.getCode() + ": " + error.getValue());
    }
    return elem;
  }
1359581
def parse_error(self, response):
        ""
        error_code = response.split(' ')[0]
        if error_code in self.EXCEPTION_CLASSES:
            response = response[len(error_code) + 1:]
            return self.EXCEPTION_CLASSES[error_code](response)
        return ResponseError(response)
66522
def create_api_error_from_http_exception(e):
    
    response = e.response
    try:
        explanation = response.json()['message']
    except ValueError:
        explanation = (response.content or '').strip()
    cls = APIError
    if response.status_code == 404:
        if explanation and ('No such image' in str(explanation) or
                            'not found: does not exist or no pull access'
                            in str(explanation) or
                            'repository does not exist' in str(explanation)):
            cls = ImageNotFound
        else:
            cls = NotFound
    raise cls(e, response=response, explanation=explanation)
1181725
def _raise_error(self, *args, **kwargs):
        
        log.debug("_raise_error(): %s" % kwargs)
        try:
            error_code = str(kwargs['code'])
        except KeyError as e:
            raise FaultyPayloadError('_raise_error(): %s' % kwargs)

        try:
            raise self._code_handlers[error_code]()
        except KeyError:
            raise UnknownWSSError()
825060
def capture_exception(self, error=None):
        # type: (Optional[BaseException]) -> Optional[str]
        
        client = self.client
        if client is None:
            return None
        if error is None:
            exc_info = sys.exc_info()
        else:
            exc_info = exc_info_from_error(error)

        event, hint = event_from_exception(exc_info, client_options=client.options)
        try:
            return self.capture_event(event, hint=hint)
        except Exception:
            self._capture_internal_exception(sys.exc_info())

        return None
392552
private void parseSoap11Fault(Document soapMessage, PrintWriter logger)
            throws Exception {
        Element envelope = soapMessage.getDocumentElement();
        Element element = DomUtils.getElementByTagName(envelope, "faultcode");
        if (element == null) {
            element = DomUtils.getElementByTagNameNS(envelope,
                    SOAP_11_NAMESPACE, "faultcode");
        }
        String faultcode = element.getTextContent();

        element = DomUtils.getElementByTagName(envelope, "faultstring");
        if (element == null) {
            element = DomUtils.getElementByTagNameNS(envelope,
                    SOAP_11_NAMESPACE, "faultstring");
        }

        String faultstring = element.getTextContent();

        String msg = "SOAP Fault received - [code:" + faultcode
                + "][fault string:" + faultstring + "]";
        logger.println(msg);
    }