Skip to content

Commit 675e853

Browse files
Create safeGetBySysId utility for safe record retrieval
This utility function simplifies fetching a GlideRecord by sys_id with built-in null checks and clear logging. It prevents repeated boilerplate code and ensures that missing records are clearly logged in sys.log. Includes an example usage for fetching an incident.
1 parent f8d0c75 commit 675e853

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# safeGetBySysId
2+
3+
> Safely fetch a GlideRecord by `sys_id` and log clearly if not found.
4+
5+
**Use case:**
6+
I often need to fetch a single record inside background scripts or Script Includes and don’t want to keep repeating the same `gr.get()` + null checks. This helper makes it a one-liner and keeps logs human-readable.
7+
8+
```javascript
9+
/**
10+
* safeGetBySysId(table, sysId)
11+
* Returns GlideRecord object or null if not found.
12+
*/
13+
function safeGetBySysId(table, sysId) {
14+
if (!table || !sysId) {
15+
gs.warn('safeGetBySysId: Missing parameters.');
16+
return null;
17+
}
18+
19+
var gr = new GlideRecord(table);
20+
if (gr.get(sysId)) {
21+
return gr;
22+
}
23+
24+
gs.warn('safeGetBySysId: No record found in ' + table + ' for sys_id ' + sysId);
25+
return null;
26+
}
27+
28+
// Example:
29+
var inc = safeGetBySysId('incident', '46d12b8a97a83110eaa3bcb51cbb356e');
30+
if (inc) gs.info('Found incident: ' + inc.number);

0 commit comments

Comments
 (0)