Scripted RREST API payload need to get for invalid JSON

Pavan_Snow_1
Kilo Guru

I have a scripted REST api and now I am trying to get the payload if it is a valid then I am able to get it as below

 

 

var payload = request.body.data;

 

 

But if third party system send invalid JSON to ServiceNow then how to capture that I have tried different ways but not able to get it.

Below is the example of invalid JSON but I am trying to get it. 

 

 

{
	"Data": {
		"Name": "test",
		"ID": "1500"
		"description": "Test description"
	}
}

 

 

 Share any solution if it is possible to get in any way.

Thanks in advance!

1 ACCEPTED SOLUTION

Pavan_Snow_1
Kilo Guru

I think we can't get the invalid JSON as payload on request.

 

View solution in original post

20 REPLIES 20

@Pavan_Snow_1 

 

In the catch block you can do as below:

 

catch(ex){

var res = {};
res["status"] = "Error";
res["message"] = ex.message;
res["Payload"] = request.body.data;
response.setBody(JSON.stringify(res)); // sending the invalid message back

}

 

If my answer solved your issue, please mark my answer as Correct & 👍Helpful based on the Impact.

 

 

Hi @Prince Arora ,

request.body.data;

 It is not working. 

@Pavan_Snow_1 ,

 

Yes, it should not work since we cannot assign an invalid response to a variable.

The behaviour is correct!

 

In general, if we take REST API as an example, whenever we do not receive a valid response from API, we will receive the error message, status code, but not the content of the response, so you can proceed with only the status and error messages. You can check examples on google for more info.

 

If my answer solved your issue, please mark my answer as Correct & 👍Helpful based on the Impact.

Hi @Pavan_Snow_1 ,

 

you can use something like below

var req = request.body.dataString;
var body = JSON.parse(req);
try{
var data = JSON.parse(body); 
}
catch(e){
    gs.log("JSON Error "+e);
}

if(data != undefined){
//do what you need with payload
}

Hi @Kamil Smusz ,

See below error

com.glide.rest.util.RESTRuntimeException: The payload is not valid JSON.
I am getting when it is invalid JSON. Errors are okay but I am trying to capture that invalid payload on the transaction record.