From 8e55556746819af191b8d5e30ab91a5ac75e911e Mon Sep 17 00:00:00 2001 From: Rajasree2004 Date: Thu, 30 Oct 2025 07:11:13 +0530 Subject: [PATCH] Add Error Handling Wrapper --- .../Error Handling Wrapper/README.md | 39 +++++++++++++++++++ .../Error Handling Wrapper/safeQuery.js | 28 +++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/README.md create mode 100644 Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/safeQuery.js diff --git a/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/README.md b/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/README.md new file mode 100644 index 0000000000..4ef8480842 --- /dev/null +++ b/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/README.md @@ -0,0 +1,39 @@ +# GlideRecord Error Handling Wrapper + +## Description +This snippet provides a **safe execution wrapper** around GlideRecord queries. +It helps avoid runtime errors due to invalid table names, malformed queries, or null references, and ensures graceful script continuation. + +--- + +## Note +- Works in global or scoped applications. +- Suitable for Background Scripts, Business Rules, or Script Includes. +- Prevents script termination from invalid GlideRecord calls. + +--- + +## Functionality +1. Validates table existence using `isValid()`. +2. Wraps GlideRecord operations in a `try...catch` block. +3. Logs detailed error messages via `gs.error()`. +4. Allows the developer to safely pass a callback for query operations. + +--- + +## Usage Example +```js +safeQuery('incident', function (gr) { + gr.addQuery('priority', 1); + gr.query(); + while (gr.next()) { + gs.info('High-priority Incident: ' + gr.number); + } +}); +``` + +## Output +``` +High-priority Incident: INC0012345 +High-priority Incident: INC0012346 +``` \ No newline at end of file diff --git a/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/safeQuery.js b/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/safeQuery.js new file mode 100644 index 0000000000..28c283f0ea --- /dev/null +++ b/Core ServiceNow APIs/GlideRecord/Error Handling Wrapper/safeQuery.js @@ -0,0 +1,28 @@ +/** + * GlideRecord Error Handling Wrapper + * Safely executes GlideRecord queries and catches runtime errors such as invalid table names or malformed queries. + * Logs detailed error information and ensures the script continues gracefully. + */ + +function safeQuery(table, queryCallback) { + try { + var gr = new GlideRecord(table); + if (!gr.isValid()) { + gs.error('Invalid table name: ' + table); + return; + } + + queryCallback(gr); + } catch (e) { + gs.error('Error executing GlideRecord query on table "' + table + '": ' + e.message); + } +} + +// Example usage: +safeQuery('incident', function (gr) { + gr.addQuery('active', true); + gr.query(); + while (gr.next()) { + gs.info('Incident: ' + gr.number); + } +});