- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-03-2024 05:55 PM
This article provides a detailed guide for developers on how to implement error logging in ServiceNow REST API calls.
Whether you're integrating external systems with ServiceNow or building custom workflows that rely on API interactions, managing and tracking errors efficiently is crucial for maintaining a robust system. In this guide, we will walk you through the steps of creating error logs, including how to handle exceptions, use system logs, and even create custom log tables for enhanced error tracking.
In ServiceNow, handling REST API calls effectively is crucial, especially when you're integrating with external systems. Ensuring that errors are logged correctly not only helps in debugging but also in monitoring the overall health of the integration. This guide will show you how to create error logs in ServiceNow when a REST API call fails, using a Script Include, as well as how to create custom error logs for more detailed tracking.
Why Log Errors?
When REST API calls are made, a variety of things can go wrong:
- The external API may be down.
- You might receive an invalid response format.
- The network could experience connectivity issues.
- Authentication or authorization failures can occur.
In any of these cases, logging these errors is essential for timely troubleshooting and ensuring the smooth operation of your integration.
Five (5) Steps to Create Error Logs for REST API Calls in ServiceNow
1. Creating a Script Include for REST API Calls
A Script Include is an ideal place to encapsulate the logic for your REST API calls. Here's how you can structure a Script Include to make the call and handle error logging.
Let’s dive into the practical aspects of error logging in ServiceNow REST API calls.
var ApiCallHandler = Class.create();
ApiCallHandler.prototype = {
initialize: function() {},
makeApiCall: function() {
try {
// Define the REST message
var r = new sn_ws.RESTMessageV2('Your REST Message', 'GET'); // Use your REST Message and HTTP method
var response = r.execute(); // Execute the REST call
var httpStatus = response.getStatusCode();
// Check if the call was successful (HTTP Status 200)
if (httpStatus == 200) {
var responseBody = response.getBody();
var parsedResponse = JSON.parse(responseBody); // Assuming the response is JSON formatted
gs.info('API Call Successful: ' + responseBody);
} else {
// Log error details when the call fails
var errorDetails = response.getErrorMessage();
gs.error('API Call Failed: ' + errorDetails);
this.createCustomErrorLog(httpStatus, errorDetails); // Optional logging to a custom table
}
} catch (ex) {
var message = ex.getMessage();
gs.error('Error in API Call: ' + message);
this.createCustomErrorLog(500, message); // Log exceptions to a custom log
}
},
// Optional: Creating a custom error log in a custom table
createCustomErrorLog: function(status, message) {
var logGr = new GlideRecord('u_custom_log'); // Replace with your custom table name
logGr.initialize();
logGr.u_status_code = status;
logGr.u_error_message = message;
logGr.insert();
},
type: 'ApiCallHandler'
};
Key Components:
- RESTMessageV2 API: This ServiceNow API allows you to send REST requests and process responses. In the above example, we make a simple GET request.
- Error Handling: We use a combination of status code checks and a try-catch block to catch all potential errors in the API call.
- System Logging: gs.error() is used to log errors into the ServiceNow system logs.
- Custom Log Table: If you want more control over your logging, you can insert error details into a custom table (e.g., u_custom_log). This gives you structured error records for reporting.
2. Adding the Script Include to Your Workflows
Once your Script Include is created, you can call it from various workflows in ServiceNow, such as:
- Business Rules: For example, create an after-insert Business Rule that calls your Script Include when certain records are created.
- Scheduled Jobs: If you're making periodic REST calls, you can use a Scheduled Job to invoke the Script Include.
- UI Actions: Trigger API calls from UI buttons or actions.
Here’s an example of how to call the Script Include from a Business Rule:
var apiHandler = new ApiCallHandler();
apiHandler.makeApiCall();
3. Logging Errors to the System Log
ServiceNow provides several methods to log errors directly into the system logs:
- gs.error(): Logs an error in the system error logs (System Logs > Errors).
- gs.warn(): Logs a warning in the system logs.
- gs.info(): For informational messages (useful for successful REST API calls).
Example:
gs.error('API Call Failed: Status ' + httpStatus + ', Message: ' + errorDetails);
These messages can be easily monitored in the System Logs section.
4. Creating Custom Logs for Detailed Error Tracking
While logging errors to the system logs is useful, there are scenarios where having custom logs in a separate table offers better reporting and monitoring options. Here’s how to create custom logs:
- Create a Custom Table: Create a new custom table (e.g., u_custom_log) with fields for storing status codes, error messages, timestamps, etc.
- Log Errors to the Custom Table: In your Script Include, use GlideRecord to insert error details into your custom log table.
var logGr = new GlideRecord('u_custom_log');
logGr.initialize();
logGr.u_status_code = status;
logGr.u_error_message = message;
logGr.insert();
This approach allows you to:
- Filter logs easily using conditions in list views.
- Set up dashboards or reports for error tracking.
- Automate notifications for critical errors.
5. Monitoring and Reporting on Errors
To keep track of your API errors, consider setting up:
- Email Notifications: Trigger notifications when a specific error is logged.
- Performance Analytics Dashboards: Create dashboards to monitor the health of your integrations and log any recurring issues.
- Scheduled Reports: Generate and send error log reports on a daily or weekly basis to the appropriate teams.
Conclusion
Proper error logging in ServiceNow REST API calls ensures that you can quickly identify issues in your integrations and take corrective actions. By leveraging system logs and custom logs, you can track every API error with detailed context, making troubleshooting much easier. Whether you’re building custom integrations or using ServiceNow's built-in REST capabilities, this error handling approach will keep your workflows smooth and error-free.
By combining Script Includes, system logging, and custom logs, you have full control over how errors are captured and reported, ensuring your integrations stay resilient.
This article has covered the essentials of implementing error logging in ServiceNow REST API calls. By following the steps outlined, you'll be able to effectively manage and track any issues that arise during API interactions, ensuring your integrations remain resilient and reliable.
For a more in-depth, hands-on demonstration, I recommend watching our live video tutorial where we walk through these concepts step-by-step. This video will provide additional context, examples, and tips to help you master error logging in ServiceNow. Don’t miss it!
Please mark as helpful if you find the article lucrative
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-03-2024 09:49 PM
When integrating external systems with ServiceNow, one of the key challenges developers face is effectively managing and logging errors that arise from REST API calls. This article is designed to equip you with the knowledge needed to implement robust error logging in these scenarios. We’ll explore how to handle exceptions, log errors to system logs, and even create custom log tables for detailed tracking. By mastering these techniques, you'll ensure that your integrations are not only efficient but also resilient to unforeseen issues. Whether you're new to ServiceNow or a seasoned developer, this guide will enhance your ability to troubleshoot and maintain API-driven workflows.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2025 06:02 PM
hello. everyone,
I have added this technique on how to handle global error handling in ServiceNow to complement what I have mentioned ☝️.
How to Implement Global Error Handling in ServiceNow for Architects and Developers
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-03-2024 09:49 PM
When integrating external systems with ServiceNow, one of the key challenges developers face is effectively managing and logging errors that arise from REST API calls. This article is designed to equip you with the knowledge needed to implement robust error logging in these scenarios. We’ll explore how to handle exceptions, log errors to system logs, and even create custom log tables for detailed tracking. By mastering these techniques, you'll ensure that your integrations are not only efficient but also resilient to unforeseen issues. Whether you're new to ServiceNow or a seasoned developer, this guide will enhance your ability to troubleshoot and maintain API-driven workflows.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2025 06:02 PM
hello. everyone,
I have added this technique on how to handle global error handling in ServiceNow to complement what I have mentioned ☝️.
How to Implement Global Error Handling in ServiceNow for Architects and Developers