Search This Blog

Thursday, October 24, 2013

ColdFusion: Error Handling

Most of time when we write code, we assume everything works like it should. However in reality, anything could happen. ColdFusion provides a way for us to handle exceptions gracefully. All these tags and the function are very useful, especially when the application interacts with third-party systems.

  • <cftry>...</cftry>
    Wrap code that could potentially cause an exception with this tag.
  • <cfcatch>...</cfcatch>
    This tag is placed inside <cftry> block. If an exception occurs, the tag would catch it; and we could handle it, such as logging the message or giving users a better error message.
  • <cfthrow />
    This tag is placed inside <cftry> block. If something did not work as expected, we could throw a custom exception and let <cfcatch> handles it.
  • <cfrethrow />
    This tag is placed inside nested <cfcatch> block. Nested <cftry>/<cfcatch> block provides a granular way to handle exceptions. If inner <cfcatch> could not handle it, we use <cfrethrow /> to send the exception to its parent.
  • onError()
    This function is placed in Application.cfc. It catches any errors that are not caught by <cftry>/<cfcatch> block. So, whether you implement <cftry>/<cfcatch> block or not in your code, it would be wise that you implement this function.

For more information about how to use those tags and function, please refers to error handling in ColdFusion documentation.

I found the referring document above is not complete. It's missing <cffinally>...</cffinally>. The tag is used to wrap processes that needs to be run before exiting <cftry>...</cftry>. Keep in mind, it is always run whether there is an exception or not. Without <cffinally>...</cffinally>, any code after <cfcatch>...</cfcatch> would cause an exception.

Some tips for writing better code:

  • Implement onError() in Application.cfc
  • Wrap code with <cftry>/<cfcatch>
  • Use <cfthrow /> for creating custom exception
  • Use <cffinally>...</cffinally> for running addtional processes after cfcatch
  • If there is nesting cftry/cfcatch, we can utilize <cfrethrow />