CF Snippets

Rethrowing errors to handle errors at the local AND global level

The rethrow function is, in my opinion, one of the coolest things ever. rethrow() lets your app catch and handle exceptions locally before rethrowing the exception to log or handle the error at a global level. This is awesomely helpful if you need to undo a transaction, for example, or to recover from any other context-specific situation.

// First level of error handling
// Say, onError in Application.cfc
try {
  // somewhere in app-land...
  try {
    // do something error-able
    x = 1 / 0;
  } catch( any e ) {
    // Recover so we don't bork the app
    transactionRollback();
    // let the parent-level catch handle error logging.
    rethrow();
  }
} catch( any exception ) {
  cfparam( name="exception.message", default="[no message]" );
  cfparam( name="exception.detail", default="[no detail]" );

  // Log it with LogBox!
  writeOutput( "Logging error with logbox..." );
  logger.error(
    "Error in cfSnippets app: #exception.message# #exception.detail#"
    exception
  );
}