The CreatorCon Call for Content is officially open! Get started here.

How to use try catch in ServiceNow Scripts

andymcdonald
Kilo Guru

I attended Steve Bell's advanced GlideRecord session at K16 and I believe there was an incidental comment made about how to properly implement exception handling in SN scripts.   However, I made no note of it and cannot remember exactly what the instructions were.   I believe there was something said about a property that needed to be set...

Anybody who knows the answer to this, please let me know.

As it is now, try catch is ignored and the script just dies.

6 REPLIES 6

Harish KM
Kilo Patron
Kilo Patron

Hello,


Sample code which I used



if(cond)


  {


  //code


}


else


  {


  try


  {


//code



  if(result==false)


  {


  //code


  }


  else


  {


//code


  }


  }catch(err)


  {


  var errText = '';


  errText += "include Script Name : abc, ";


  validate.updateExitLog(errText);


  }


}


Regards
Harish

Ha! No, I'm not asking how to use try…catch. I'm asking how to make ServiceNow play nice with it. As it is, it does not send an error to the catch block. Instead, it just eats it and exits the script as if there were no try catch at all.



My point is that I heard Steven make a comment about this and I think it involved setting a system property to make this happen; sadly, I did not write it down and have lost the information.



Andrew McDonald


ITSM/ITSM API Development - 480.370.1128


I've run into the same problem. I have a workflow script with a try..catch that calls a script include. I noticed it catches an error thrown during object initialisation but it won't catch an error thrown by the object after it has been new'd



I posted a more detailed explanation of what I had tried. Using try catch in workflow doesn't catch errors


Did you get anywhere with your issue or find the K16 session notes?


Daniel Oderbolz
Kilo Sage

Dear Andrew



What I typically do in Script includes is this:



snow_try_catch.js · GitHub



The call to gs.error is not really neededm but I do create an event with the location and the error.


What I did not manage yet is to determine the location using code rather than constants.



Best


Daniel



If this post was helpful, I would appreciate if you marked it as such - thanks!

Best
Daniel