Trapping Errors
The application below is a simple ColdFusion template. It retrieves data from a database and displays it within an HTML table. But unlike other templates, it uses Structured Error Handling to trap any exceptions thrown.
To do so, this example encloses the entire listing within a try block. The code starts with a <CFTRY> and ends with a </CFTRY>. The code at the bottom of the listing is to catch blocks. The first is a database catch block; it traps any exceptions thrown by the <CFQUERY> tag. If an exception is thrown, the user sees an explanatory error message (and not any database errors), and an e-mail message is sent to the administrator describing the problem. The second catch block catches all other exceptions. An email message is sent to the administrator, and the user is then rerouted to a feedback screen using the <CFLOCATION> tag.
Structured Error Handling Source Code Example
<!--Sample Application Using Structured Error Handling--> <!--Start try block--> <CFTRY> <!--Get Inventory--> <CFQUERY DATASOURCE="myDSN" NAME="books"> SELECT Emp_Fname, Emp_Lname FROM Employee ORDER BY Emp_Lname </cfquery> <!--Display names--> <TABLE BORDER="1"> <tr> <th>FirstName</th> <th>Lastname</th> </tr> <CFOUTPUT QUERY="books"> <tr> <td>#Emp_Fname#</td> <td>#Emp_Lname</td> </tr> </cfoutput> </table> <!--Database catch block--> <CFCATCH TYPE ="Database"> <!--Feedback to user--> Sorry, we are experiencing database problems at this time. Please try your search again later. <!--Send E-Mail to the admin--> <CFMAIL TO="myemail@mailserver.com" FROM="myemail@mailserver.com" SUBJECT="EXCEPTION: #CFCATCH.type#"> Message: #CFCATCH.message# Error Code: #CFCATCH.nativeerrorcode# SQL State: #CFCATCH.sqlstate# Detail: #CFCATCH.detail# </cfmail> <!--All other errors--> <CFCATCH TYPE ="Any"> <!--Send Email to the admin--> <CFMAIL TO ="myemail@mailserver.com" FROM="myemail@mailserver.com" SUBJECT="EXCEPTION: #CFCATCH.type#"> Message: #CFCATCH.message# Detail: #CFCATCH.detail# </cfmail> <!--Send the user to the feedback page--> <CFLOCATION URL="feedback.cfm"> </cfcatch> </cftry>

