Not yet rated

Problem

A ColdFusion application needs to handle errors that aren't handled in try/catch blocks.

Solution

The method onError() in Application.cfc will allow an application to handle errors that are not handled by individual try/catch blocks.

Detailed explanation

The onError() method in ColdFusion provides a way to handle any exceptions that are not handled by individual try/catch blocks.  It is placed in the Application.cfc

<cffunction name="onError" access="public" returntype="void">
</cffunction>

The onError() method takes two arguments.EventName, which is a string and Exception, which is a structure. The EventName will be one of the following:


onApplicationStart
onSessionStart
onRequestStart
onRequest
onRequestEnd
onApplicationEnd 
onSessionEnd

With the onApplicationEnd and onSessionEnd events the application is not able to display an error message to the user, however the application is able to log errors that occur during these events.

The Exception structure is identical to that of the <cfcatch> tag.  The <cfcatch> tag details can be found here: http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7ec5.html

The method should look like the following:

<cffunction name="onError" access="public" returntype="void">
<cfargument name="Exception" required="true" type="struct" />
<cfargument name="EventName" required="true" type="string" />
</cffunction>

The application can send and email or create an entry in a log when an error occurs as well as show a message to the user.

In order to display a simple error message to the user the application should check to make sure the event is not onSessionEnd or onApplicationEnd.  

Once this is done an error message can be coded in the function or included using <cfinclude>.

The final onError() method should look as follows:

<cffunction name="onError" access="public" returntype="void">
<cfargument name="Exception" required="true" type="struct" />
<cfargument name="EventName" required="true" type="string" />

<cfif NOT (Arguments.EventName IS "onSessionEnd") OR
(Arguments.EventName IS "onApplicationEnd")>
<cfinclude template="globalErrorTemplate.cfm" />
</cfif>

</cffunction>

ColdFusion had made implementing a global error handler easy with the use of
the onError() method.

 

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes