CF Snippets

Error Handling in CFML

Honestly, the simplistic it-just-works error handling in CFML is one of my favorite features of the language. With a three-part error handling strategy of 1. inline try-catch-rethrow, 2. application-level exception listener, and 3. LogBox for advanced email/file/console/database error logging, you really can't go wrong.

Global Error Logging from Application.cfc

The onError function in Application.cfc is a great way to catch errors within your application and make sure that each error is logged. Be aware that if you catch an exception within your app, that exception will not "bubble up" to this onError handler unless you also use rethrow.
// Application.cfc
component {
  // ...
  function onError( exception ){
   // Log it with LogBox!
    writeOutput( "Logging error with logbox..." );
    logger.error(
        "Error in cfSnippets app: #exception.message# #exception.detail#"
        exception
    );

    // show error page
    include "views/error.cfm";
  }
}

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
  );
}

Get New Snippets In Your Inbox

No spam, not too many emails.