JavaScript Exception Handling
When writing JavaScript business rules, it is important that 'try…catch' statements are designed correctly. 'Try...catch' statements should not swallow (catch and ignore) exceptions that should cause changes made by the script to be rolled back and cause the business rule to fail.
Important: Carelessly swallowing exceptions will lead to derived errors, which usually makes it very hard to determine the root cause.
The sample code in the table below demonstrates a way to log exceptions in JavaScript without swallowing those that should be handled by the framework.
Correct |
Incorrect |
---|---|
try { // Some code } catch (e) { logger.info(e); throw(e); // REQUIRED } |
try { // Some code } catch(e) { logger.info(e); } |
The only types of JavaScript exceptions that may be caught and handled locally are:
- Checked exceptions thrown by an invoked method (including any subclasses of the specified checked exception) (refer to the example below)
- Exceptions not generated by calls to the STEP API
Important: Any other exception must always be re-thrown if caught, or not caught at all.
Correct Handling of Checked Exceptions
The code snippet below exemplifies how a checked exception can be caught and handled locally. Notice the necessary Rhino specific 'e.javaException' notation.
try {
currentObject.createReference(targetAsset, primaryImageRefType.getID());
} catch (e) {
if (e.javaException instanceof com.stibo.core.domain.UniqueConstraintException) {
logger.info("Reference could not be created");
} else {
throw(e); // All other exceptions MUST be re-thrown
}
}