Friday 3 September 2021

Remove/replace xml tags and xml nodes from the error response to make valid json format in SAP CPI


Remove the xml tags and send only the error text to the target system from the exception process/negative response.

Groovy Script:

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.lang.*
def Message processData(Message message) {
def body = message.getBody(java.lang.String) as String;
body = body.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim(); //Replace xml node
body = body.replaceAll("<error xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">","").trim();
body = body.replaceAll("<code>ERROR</code>", "").trim();
body = body.replaceAll("</message>", "").trim();
body = body.replaceAll("<message xml:lang=\"sv\">", "").trim();
body = body.replaceAll("<error>", "").trim();
body = body.replaceAll("</error>", "").trim();
body = body.replaceAll("\\\t|\\\n|\\\r","");
message.setBody(body);
return message;
}

Input:

{
"Response":
    {
    "status": "Error",
    "statusCode": "500",
    "C4CObjectID": "",
    "error": "<?xml version="1.0" encoding="utf-8"?><error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><code>ERROR</code><message xml:lang="sv">Invalid syntax in email address</message></error>"
}
}

Output:

{​​​​​​​​
"Response":
{​​​​​​​​
"status": "Error",
"statusCode": "500",
"C4CObjectID": "",
"error": " Invalid syntax in email address" }​​​​​​​​}​​​​​​​​



1 comment: