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.

Additionally, only catching an exception without rethrowing it can lead to inconsistent data or the error: 'The transaction cannot be committed, because it was already marked for rollback only. The transaction will be rolled back instead.'

Important: Carelessly catching and ignoring exceptions will lead to derived errors, which usually makes it difficult 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 demonstrates how a checked exception can be caught and handled locally, including the necessary Rhino specific 'e.javaException' notation.

Copy
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
}
}