The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Error handling in Scripted REST API for JSON format issue

Ganeshm1
Tera Guru

Hi All,
Hope you are doing well.

I created one scripted rest API and its not working as expected for the below case where Request body is not in proper JSON format. 

If I pass the below proper JSON Format, its working as expected. 

 

{
  "number": "1234",
   "correlation_id": "55556667777788889",
  "location_id": "test"
}

 

But when I pass the below improper JSON format, its giving status code as 200 and empty response.
Same issue I observed in REST API Explorer as well.

 

{
  "number": "1234",
   "correlation_id": 55556667777788889,
  "location_id": "test"
}

 

Ganeshm1_0-1758808393423.png

 

Please let me know how I can add a validation if request body is a valid JSON or not in this use case. Thank You!

 

Best Regards,
Ganesh

1 REPLY 1

JenniferRah
Mega Sage

The tricky thing here is that the second example is actually proper JSON since the correlation_id is composed of just numbers. It is probably just reading it as a number rather than a string. Could you convert it to a string in your code to get by the issue?

 

If you are missing a parameter that is not sent at all, you can check for that and then return an error message. It would look something like this: 

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    var requestBody, responseBody, status, sm;

    try {
        requestBody = request.body;
        var JSONdata = new global.JSON().decode(requestBody.dataString);

        if (JSONdata.number == null || JSONdata.correlation_id == null || JSONdata.location_id == null) {
                    return {
                        "status": "Error",
                        "message": "Missing required parameters.",
                    };
        } else {
            //do stuff
            return {
                "status": "Success",
                "message": "Action completed successfully",
            };
        }
    } catch (ex) {
        res["status"] = "500";
        res["message"] = "An error has occurred";
        response.setBody(JSON.stringify(res));
        status = '500';
    }

})(request, response);