在Javascript中捕获SOAP错误

时间:2019-06-25 14:58:40

标签: javascript xml soap

我需要一种方法来处理Javascript(反应)中的SOAP错误。我的SOAP请求不是直接从React发出的,而是从Node.js(我用作代理服务器)发出的。

我已经尝试过的:

fetch("/FreePUOrderNo", {
      crossDomain: true,
      method: "POST",
      withCredentials: true,
      headers: {
        Accept: "text/xml",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        puOrderNo: puOrderNo
      })
    }).then(response => response.text())
      .then(str => {
        dataAsJson = convert.xml2json(str);
        console.log(dataAsJson);

此刻,响应如下:

{"elements":[{"type":"element","name":"s:Envelope","attributes":{"xmlns:s":"http://schemas.xmlsoap.org/soap/envelope/"},"elements":[{"type":"element","name":"s:Body","elements":[{"type":"element","name":"s:Fault","elements":[{"type":"element","name":"faultcode","attributes":{"xmlns:a":"urn:microsoft-dynamics-schemas/error"},"elements":[{"type":"text","text":"a:Microsoft.Dynamics.Nav.Types.Exceptions.NavNCLDialogException"}]},{"type":"element","name":"faultstring","attributes":{"xml:lang":"en-US"},"elements":[{"type":"text","text":"You cannot Modify or Perform Actions in Cancelled PU Order."}]},{"type":"element","name":"detail","elements":[{"type":"element","name":"string","attributes":{"xmlns":"http://schemas.microsoft.com/2003/10/Serialization/"},"elements":[{"type":"text","text":"You cannot Modify or Perform Actions in Cancelled PU Order."}]}]}]}]}]}]}

所以,我做了什么,以获取“您无法在已取消的PU订单中修改或执行操作”。是这个吗?

if ("faultcode" in dataAsJson) {
          const res =
          dataAsJson["elements"][0].elements[0].elements[0].elements[1].elements[0].text;
          console.log(res);
        }

我收到此错误:

Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'faultcode' in {"elements": .... }]]}}]}

我不知道为什么会收到此错误,因为我对一个对象使用了“ in”运算符。另外,我不知道其他任何处理SOAP请求中错误的方法。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

所以,我当前的解决方案是:我对服务器响应进行了字符串化,检查其是否包含.includes中的'faultcode'(或'faultstring'),然后对其进行解析以获取我想显示的信息用户。

 .then(response => response.text())
      .then(str => {
        dataAsJson = convert.xml2json(str);
        const dataAsString = JSON.stringify(dataAsJson);
        if (dataAsString.includes("faultcode") === true) {
          const parseData = JSON.parse(dataAsJson);
          const res = parseData["elements"][0].elements[0].elements[0].elements[1].elements[0].text;
          alert(res);
        }

不确定这是否是一个好的解决方案,因此欢迎提出任何想法!