Have you ever had to troubleshoot an error in ServiceNow, only to find that the log message provided little to no context? You open the logs hoping for insight, but all you see is a generic error message. Now, you're left hunting through a script, possibly a lengthy Script Include, just to pinpoint the issue.
This is where NiceError can help. NiceError is an out of the box object designed to provide you context when the error occurs. You will be able to see the line number in the script where the error occurred, saving you time and frustration. You will also be provided a stack trace, meaning you get information about the functions that were used prior to the error happening. This information is highly useful when troubleshooting errors in the code.
Traditional log messages
Imagine that you have a before business rule which is doing some checks on the content of an Incident before it is inserted into the database. The business rule might look like this:

Imagine a user trying to create an Incident that does not pass the validation performed in the business rule like the following:

This will generate the following error message in the system log:

The problem? This log message lacks context. The developer investigating the issue has to dig into the code, trace function calls, and possibly experiment to understand the root cause. In a simple example, this might not be too difficult, but if the error originates from a large Script Include with multiple function calls, troubleshooting can become time consuming.
Improvement with NiceError
To enhance the error logging and provide more context, we can integrate NiceError into our script. Let's take a look at how this works.
If we modify our Script Include to use NiceError, we can insert a new instance of the NiceError object at the point of failure:

What the NiceError will do:

In this example we see that the script generating the error has the sys_id "16b243ef53c86210030191e0a0490e80" and that the error happend on line 7, in the "verifyContent" method.
With this enriched error message, developers can quickly identify what went wrong and where, leading to faster troubleshooting and resolution times.
Conclusion
If you’re working with complex ServiceNow scripts, NiceError is a game-changer for debugging. By adding meaningful context to error logs, it helps developers diagnose issues faster. Next time you’re dealing with cryptic log messages, consider using NiceError, because better logs mean less frustration and quicker fixes.