- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 05:47 AM
Hi,
I have a script where i'm performing insert to a certain table. i wrapped that script with try - catch statement.
I noticed that in case i try to insert, and there is a error due to Unique Key violation - they script does not got to the catch statement.
Would like to get some advise on how to handle such case.
Solved! Go to Solution.
- Labels:
-
Scripting and Coding
-
Team Development

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 08:47 AM
Exactly.
The return value is described as: "Unique ID of the inserted record, or null if the record is not inserted."
var id = '11111111111111111111';
var gr = new GlideRecord('my_table');
gr.initialize();
gr.setValue('id',id);
if (gr.insert() == null)
{
gs.info('Gosh! That failed :(');
}
else
{
gs.info('Yeehaa! That worked :D');
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 08:53 AM
ok, thanks - i'll use that. i thought there is a way to catch it as part of the try-catch.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 09:01 AM
I know this point of view is debatable. In my opinion, throwing exceptions anywhere in your code and not catching them is downright anti-social and irresponsible. Imagine someone disposing their garbage by throwing it over the fence into the neighbor's garden.
Let's assume most of us are kind, responsible human beings (when writing code).
Based on that, assume that no exceptions are thrown to your garden by code written by someone else.
So look out for return values first.
If someone else's code throws exceptions into your code, wrap the code into a function and provide the result as a return value.
Like this function here:
The DevTools app contains a truckload of reusable scripts and
features to support your app development.
Fork at will!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 08:27 AM
this is a sample of the code:
try{
var id = '11111111111111111111';
var gr = new GlideRecord('my_table');
gr.initialize();
gr.setValue('id',id);
gr.insert();
}
catch(e){
gs.print('TRY CATCH');
}

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-10-2022 08:53 AM
I assume what you try to do is to insert a record (if it does not exist already). And maybe even update an existing record if it exists already.
This function can help with that:
The DevTools app contains a truckload of reusable scripts and
features to support your app development.
Fork at will!