Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Try catch in script include

Geeky
Kilo Guru

Hi,

I am publishing a scripted web service and have code in the script include. For better error handling of an unexpected error, thinking of using try-catch block.

Can anybody share a code snippet of how to use a try-catch block for displaying the error message in response to the API call?

6 REPLIES 6

Dylan Mann1
Giga Guru

Here's a script generated by SN, I just added the log at the bottom. Cheers

try { 
 var r = new sn_ws.RESTMessageV2('My End Point', 'get');
 r.setStringParameterNoEscape('symbol', '');

//override authentication profile 
//authentication type ='basic'/ 'oauth2'
//r.setAuthenticationProfile(authentication type, profile name);

//set a MID server name if one wants to run the message on MID
//r.setMIDServer('MY_MID_SERVER');

//if the message is configured to communicate through ECC queue, either
//by setting a MID server or calling executeAsync, one needs to set skip_sensor
//to true. Otherwise, one may get an intermittent error that the response body is null
//r.setEccParameter('skip_sensor', true);

 var response = r.execute();
 var responseBody = response.getBody();
 var httpStatus = response.getStatusCode();
}
catch(ex) {
 var message = ex.message;
 gs.error("Error in system logs: " + message);
}

How can I store request body received from third party tool, response sent from SN and error messages for any troubleshooting purposes? Do I need to create a custom table to store them?

You certainly could do that, here's a post showing how you can view a log of REST API activity. 

https://community.servicenow.com/community?id=community_question&sys_id=726c07a5db9cdbc01dcaf3231f96...

Not sure if it satisfies what you're looking for but could be useful.

Sufiyan Memon
Kilo Sage

Hi Geeky

You can use following try/catch structure for that.

try {

// Code will be here in which you are expecting to get error

}

catch(err){   

var error_message = err.message;

// error_message variable will have the error message that you can use for further. 

}

 

Please mark as correct if it resolve your issue or let me know if further explanation needed.

Thanks