How to remove initial string preceding an object

Viewed 42

I am getting a response in this format:

javax.xml.rpc.ServiceException: [{"ReturnCode":0,"counter":"\\\\sap\\CTI \\CTIConnection"},{"ReturnCode":101,"ErrStr":"\\\\10.77.44.101\\CTI Manager\\CTIConnectionActive;","counter":"\\\\10.77.44.10\\CTI Manager\\CTIConnectionActive"}]

Now the issue is coming from javax.xml.rpc.ServiceException: preceeding the object. I want to show an error message after checking the ReturnCode, but currently the only way it works is by splitting the javax.xml.rpc.ServiceException: part. The below code works:

 let errorObj = JSON.parse(errRes.error.split(': ')[1]);
let filteredError =  (errorObj.filter(val => {  
              if(val.ReturnCode !== 0) {    
                return val.ErrStr   
              } 
            }));    
           this.errorArr = filteredError.map(a => a.ErrStr);    
           let errServer = this.errorArr.map((err) => { 
            return err.split('\\')[2];  
           }).join(' ; ')

But, my problem is if the object contains some other error messages, then the above code will not work as expected. So, I want an alternate way where I don't have to split the string and modify. Is there a way to check the type and then omit the string part at the beginning if it exists and then do the calculation, and if it does not exist (its a JSON object), then it will do the regular map. I am not able to figure out how to do that. Please help. Thanks in advance.

1 Answers

How about a regex?

const text = "your response text";
const matchJava = text.match(/java.*?: (.*)/);
const matchAnything = text.match(/^.*?:\ (.*)/);
const match = matchJava || matchAnything;
console.log(match ? match[1] : text);

Although ideally your backend programmer should stop returning mangled data and return proper HTTP status code + parsable response.

Perhaps try with Accept: application/json (or any other format you expect) if the server isn't already doing that. Otherwise you're out of luck and you need to parse.

Related