Error- and Exception-Handling Layers


ColdFusion provides different layers to handle errors. When an error occurs within the ColdFusion template, the first layer is invoked through the <cftry>, <cfcatch>, <cfthrow>, and <cfrethrow> tags. If this layer fails, a second layer is activated using the <cferror> tag. If this fails too, the ColdFusion Administrator sitewide handler activates the third layer. If no sitewide handler has been defined, the default error message is displayed. You can prevent an error that occurs during a <cfquery> or <cfstoredproc> database operation by using the <cftransaction> tag protection layer.

The Standard Error Format and Error Variables

If no error-handling layer is present, the standard error message is displayed in the browser. Figure 14.1 displays the standard error format.

click to expand
Figure 14.1: The standard error format.

The standard error format consists of these sections:

  • Error description. Provides a brief online description of the error.

  • Error message. Offers a detailed description of the error. For example, if you have specified an invalid attribute for a tag, this section includes a list of valid tag attributes.

  • Error location. Displays the page and line number where ColdFusion encounters the error. It also has a short section of CFML that includes the error line.

  • Error environment information. Provides information about the request that caused the error. It includes the end user browser, the end user IP address, and the date and time of the error.

  • Resources. Displays the links to Knowledge Base, documentation, and other resources that help to resolve the problem.

  • Stack trace. Identifies the Java stack and Java class at the time of exception. The stack trace is collapsed by default.

Check system parameters, such as disk space and available memory, if the message doesn't identify the cause of the error.

Using the <cferror> Tag

This tag specifies custom error pages. The <cferror> tag enables ColdFusion to handle errors at a more general level than the <cftry> and <cfcatch> block. Since custom error pages apply to an entire application, it's more appropriate to place this tag inside the Application.cfm template. You can specify these types of custom error messages:

  • Validation. Handles server-side form field validation errors when a form is submitted. This page cannot include CFML tags or functions but can display error page variables.

  • Request. Serves as the default option and handles any errors generated during a template request. This option can only use certain error variables. It cannot use CFML tags.

  • Exception. Handles specific exception errors specified in the exception attribute of the <cferror> tag. You can specify individual error pages for different types of exceptions. This option can use all CFML tags.

Table 14.1 lists the variables of the <cferror> tag.

Table 14.1: List of <cferror> Tag Variables

Tag Variable

Description

Error.Browser

Gives the type of the browser viewing the template.

Error.Diagnostic

Provides detailed information regarding the error provided by the ColdFusion server.

Error.DateTime

Indicates the date and time when the error occurred.

Error.HTTPRefer

Gives the URL of the template where the error occurred while executing.

Error.Template

Specifies the name of the template that caused the error.

Error.MailTo

Provides the e-mail address specified in the mailto attribute of the <cferror> tag.

Error.RemoteAddress

Indicates the IP address of the remote client that made the request that caused the error.

Error.QueryString

Gives the URL string of the client, if any.

Error.GeneratedContent

Provides the content generated prior to the error.

Error.ValidationHeader

Specifies the header text for a validation message template.

Error.ValidationFooter

Indicates the footer text for a validation message template.

Error.InvalidFields

Provides an unordered list of validation errors that occurred in the form.

The syntax of the <cferror> tag is

 <CFERROR TYPE="exception" TEMPLATE="site-wide.cfm" EXCEPTION="Any"           Mail to="developer@organisation.net"> 

This code invokes the site-wide.cfm template whenever any exception occurs. The site-wide template can either display error messages or provide solutions. You can specify the path of this template in ColdFusion Administrator. You can use error variables within the <cferror> tag. This is a sample of the site-wide.cfm template:

 <HTML> <HEAD><TITLE>SITE-WIDE.CFM TEMPLATE</TITLE></HEAD> <BODY>     The Web page you are trying to access is currently unavailable.     Please try later. We are sorry for the inconvenience.     <CFIF IsDefined("error.mailto">       For any further query, you can contact #error.mailto#.     </CFIF> </BODY> </HTML> 

Using the <cftry> and <cfcatch> Tags

The <cftry> and <cfcatch> tags identify the probable area of code where an error may occur, and then help you to deal with it. Write the code within the <cftry> tags. Place the code where you think the error might occur within the <cfcatch> block. You can wrap either the entire code or just the code snippet where you expect the error to occur within the <cftry> block.

Note

If you've worked with Java, C++, or Visual C++, you'll be familiar with the try/catch method. <cftry > and <cfcatch> work on the same principle.

The syntax for <cftry>/<cfcatch> is

 <CFTRY>     Write the lines of code that may cause a problem/error here.     <CFCATCH>       Write the lines of code to handle the errors here.     </CFCATCH>     <CFCATCH>       Can handle more than one error by using multiple cfcatch tags.     </CFCATCH> </CFTRY> 

You can also create nested <cftry> blocks. The <cfcatch> tag creates some variables that can be accessed only while using <cfcatch>. Prefix these variables with <cfcatch> to access them. Here are the variables created by <cfcatch>:

  • cfcatch.Detail. Provides details of the error and is similar to the default error message. The message comes from the ColdFusion Application server and is HTML-formatted.

  • cfcatch.Errnumber. Supplies the internal expression number of the error.

  • cfcatch.ErrorCode. Takes its value through the <cfthrow> tag's errorcode attribute. It works with the database or application type of exception only. Alternately, it remains empty.

  • cfcatch.ExtendedInfo. Works with cfcatch, whose type attribute is set to Application. It displays information pertaining to the error message. For any other attribute, this value remains empty.

  • cfcatch.RootCause. Stores the root cause of the exception identified by the JVM as a Java servlet exception.

  • cfcatch.Message. Offers the diagnostic information provided by the exception that occurred. This variable remains empty if no message is provided. The detail variable contains more data than this variable.

  • cfcatch.TagContext. Provides the name and position of each tag in the tag stack, along with the full path of the template. The tag stack contains data pertaining to each open tag.

  • cfcatch.NativeErrorCode. Takes the value from the error message provided by the database drivers. Alternately, it contains a value of -1.

  • cfcatch.SQLState. Contains the error code provided by the database driver in case of a failure. If no value is provided, it takes -1 as the value.

  • cfcatch.Sql. Holds the SQL statement sent to the data source.

  • cfcatch.queryError. Contains the error message as reported by the database driver.

  • cfcatch.where. Holds the query parameter name/value pairs if the query uses the <cfqueryparam> tag.

  • cfcatch.lockName. Contains the name of the lock that caused the error. If this value isn't known, the value is set to anonymous.

  • cfcatch.lockOperation. Contains the type of lock operation that failed. If this name isn't known, the value is set to unknown.

  • cfcatch.missingFileName. Contains the name of the template that <cfinclude>, <cfmodule>, or <cferror> couldn't locate.

  • cfcatch.Type. Provides the exception's type as specified in the <cfcatch> tag. This variable is returned as a string value.

cfcatch.Tagcontext is an array of structures. The list of structures in cfcatch.Tagcontext is

  • Id. The name of the tag within the stack.

  • Template. The full path to the template containing the tag.

  • Line. The line where the tag is located on the page.

  • Raw_Trace. The raw Java stack for the error.

  • Type. The type of page (it's always CFML).

  • Column. This is now obsolete, but has been retained for backward compatibility. Its value is always 0.

The following code catches a database error:

 <!--- the code is trying to insert a row in errortab table --- > <CFTRY> <HTML> <HEAD> <TITTLE>Example of CFTRY/CFCATCH tag</TITLE> </HEAD> <BODY>     <CFTRANSACTION>     <CFQUERY NAME="insert_error" DATASOURCE="Errordb" DBTYPE="ODBC">       Insert into errortab(errorbrowser, errordate, errortemplate,                              remoteadddress, diagnostic)       values('#Form.browser#', '#Form.errordate#', '#Form.template#',       '#Form.remoteaddress#', '#Form.diagnostics#')     </CFQUERY>     </CFTRANSACTION>     <!--- catch the database error if the query fails --- >     <CFCATCH TYPE="Database">       <H3> The transaction was not successful. There was a database error. </H3>       <P>       The Error information is as follows:       <BR><HR>       <UL>       <CFOUTPUT>         <li> SQL Status: - #cfcatch.sqlstae#         <li> Type: - #cfcatch.type#         <li> Template: - #cfcatch.template#         <li> Error message: - #cfcatch.message#       </UL>       <BR>       Details : - #cfcatch.detail#       </CFOUTPUT> </BODY> </HTML> </CFTRY> 

The following code handles missing template errors:

 <CFTRY> <HTML> <HEAD> <TITLE>Missing template error</TITLE> </HEAD>     <CFINCLUDE TEMPLATE="c:\Inetput\wwwroot\Mydir\myfile.cfm">     <CFCATCH TYPE="MissingInclude">     <!--- Notify the developer --- >     <CFMAIL TO=developer@organisation.com              FROM=errorexample@example.net              SUBJECT="Missing template error">       Dear developer,       The #cfcatch.missingfilename# is not locatable. Please investigate.       Regards       Website Manager     </CFMAIL>     The template you are trying to reach seems to be missing. We have notified     the authorities. Inconvenience is regretted.     </CFCATCH>     <CFCATCH TYPE="Any">       <CFOUTPUT>         An unknown error has occurred whose information is as below.       <CFOUTPUT>       <PRE>         #cfcatch.detail#       </PRE>     </CFCATCH> </HTML> </CFTRY> 

Using the <cfthrow> and <cfrethrow> Tags

Some ColdFusion tags throw exceptions automatically if they occur during execution. Certain programs don't cause errors, but produce unpredictable results, such as logical errors. In these cases, you can use the <cfthrow> and <cfrethrow> tags to generate exceptions. This is known as custom error or exception handling. Errors generated by these tags are also handled by the <cftry> and <cfcatch> tags. The following is the syntax for the <cfthrow> tag:

 <CFTRY>     Write the lines of code that may cause the error here.     <CFIF error condition>       <CFTRHOW>     </CFIF>     <CFCATCH>       Write the lines of code to handle the error here.     </CFCATCH> </CFTRY> 

The <cfthrow> tag allows you to specify your own exception types. Based on application logic, custom error messages are thrown from the custom tag back into the calling template. When working with the <cfthrow> tag, you create the error and check for it using the <cfif> tag. It throws the error to the first <cfcatch> specified.

These are the attributes of the <cfthrow> tag:

  • Errorcode. Allows you to create an error code that is meaningful to the application. Preferably, this should be numeric.

  • Message. Allows you to customize the error message for the exception you're raising.

  • Detail. Permits you to add a detailed error message for the exception.

  • ExtendedInfo. Allows you to add more information that might be useful to the application.

  • Type. Indicates the type of error. The error can be predefined or a custom type.

The following syntax throws a database exception:

 <CFTRY>     Write the code to generate a custom error.     <CFIF condition to check for error>       <CFTHROW TYPE="custom error name">     </CFIF>     <CFCATCH TYPE="custom error name">       Write the code to handle the error here.     </CFCATCH> </CFTRY> 

You can create an exception, myexcep.requiredparameter.myapp, using <cfthrow>:

 <CFTHROW type=" myexcep.requiredparameter.myapp"> 

You can use the following ways to catch the myexcep.requiredparameter.myapp exception:

 <CFCATCH type=" myexcep.requiredparameter.myapp"> <CFCATCH type=" myexcep.requiredparameter"> <CFCATCH type=" myexcep"> 

You can use the following lines of code to override pattern-matching behavior:

 <CFCATCH TYPE=" myexcep.requiredparameter.myapp"> <CFSETTING CATCHEXCEPTIONBYPATTERN="No"> 

You can use this tag to handle form field validations. Create a form with four text boxes: firstname, lastname, phone number, and date of birth. Ensure that firstname and lastname aren't empty.

The following code uses <cfthrow> to handle form field validations:

 <CFTRY> <HTML> <HEAD> <TITLE>CFTHROW Example - Form1.cfm</TITLE> </HEAD> <BODY>     <FORM METHOD="Post" ACTION="formvalidate.cfm">       <INPUT TYPE="Text" NAME="fname">       <INPUT TYPE="Text" NAME="lname">       <INPUT TYPE="Text" NAME="Phoneno">       <INPUT TYPE="Text" NAME="dob">       <INPUT TYPE="submit" VALUE="Submit Form">     </FORM> </BODY> <HTML> </CFTRY> <CFTRY> <HTML> <HEAD> <TITLE>CFTHROW Example - Formvalidate.cfm</TITLE> </HEAD> <BODY>     <CFIF form.fname EQ " ">       <CFTHROW TYPE="blankfirstname" ERRORCODE="FN01"               MESSAGE="You cannot leave firstname blank. Please try again."               DETAIL="The error is caught by CFTHROW tag on form1.cfm template">     <CFELSEIF form.lname EQ " ">       <CFTHROW TYPE="blanklastname" ERRORCODE="FN02"               MESSAGE="You cannot leave lastname blank. Please try again."               DETAIL="The error is caught by CFTHROW tag on form1.cfm template">     </CFIF>     <CFCATCH TYPE="blankfirstname">     <CFOUTPUT>       #cfcatch.message#     </CFOUTPUT>     <CFCATCH TYPE="blanklastname">     <CFOUTPUT>       #cfcatch.message#     </CFOUTPUT>     <BR>       Form submitted. </BODY> <HTML> </CFTRY> 

The following code throws a database exception:

 <CFTRY> <HTML> <HEAD> <TITLE>CFTHROW Example - database_error.cfm</TITLE> </HEAD> <BODY>     <CFQUERY DATASOURCE="Emp" NAME="myquery">       select * from employee where employeename="Anne"     </CFQUERY>     <!--- if there is no matching record found you can make ColdFusion to throw     an error --- >     <CFIF myquery.Recordtime EQ 0>       <CFTHROW TYPE="Record_not_found" ERRORCODE="DB01"                MESSAGE="There are no matching records found"                DETAIL="The error is caught by CFTHROW tag on database_error.cfm                template">     </CFlF>     <CFCATCH TYPE=" Record_not_found">     <CFOUTPUT>       #cfcatch.message#     </CFOUTPUT>     <CFCATCH TYPE="Database">       The database is currently not available. Try again later.     </CFCATCH> </BODY> <HTML> </CFTRY> 

Although you may have a <cfcatch> block, it may not be explicitly designed to handle errors. You can rethrow the exception so that a more qualified error handler can deal with it. The <cfrethrow> tag is also very useful for nested <cftry>and <cfcatch> blocks. You can create a hierarchy of error handlers with this tag. This tag rethrows the active exception to another <cfcatch>. It preserves the values of the type and tagcontext variables because they're required for further processing.

The syntax for the <cfrethrow> tag is

 <CFTRY> <CFTRY>     Write the code that may cause an error.     <CFCATCH TYPE="Type of error">     <CFIF condition to check for error you wish to handle>       Write the code to handle the error     <CFELSE>     <CFRETHROW>     </CFIF>     </CFCATCH> </CFTRY> <CFCATCH TYPE="custom error type of error">     Write the general error handling code here. </CFCATCH> </CFTRY> 

The following code uses the <cfrethrow> tag to handle database exceptions:

 <HTML> <HEAD> <TITLE>CFRETHROW Example - rethrow_ex.cfm</TITLE> </HEAD> <BODY bgcolor="yellow">     <!--- Rethrow a DATABASE exception. ---> <CFTRY>     <CFTRY>         <CFQUERY NAME="myquery" DATASOURCE="mydb">             SELECT * FROM customer         </CFQUERY>     <CFCATCH TYPE="DATABASE">       <!--- Ignore the 50555 error,otherwise rethrow the exception. --->         <CFIF CFCATCH.sqlstate neq 50555>             <CFRETHROW>         </CFIF>     </CFCATCH>     </CFTRY> <CFCATCH>     <h2> Sorry, your request cannot be processed. Database is under repair.          Try again later. </h2> </CFCATCH> </CFTRY> </BODY> </HTML> 

Configuring Error Messages with ColdFusion Administrator

When the cftry and cfcatch block and the <cferror> tag fail to handle an error, the site-wide error template comes into play. This template executes only if all other error-handling layers fail. If this layer fails too, the default error message is displayed to the end user. You can choose a template to handle errors under the Settings menu option of ColdFusion Administrator. To change these settings, do the following:

  1. Create a template that contains the code for the error you wish to handle.

  2. Go to the ColdFusion Administrator page.

  3. Choose the Settings menu option from the left panel. The right panel displays the options for this menu.

  4. Select the Site-Wide Error Handler text box option.

  5. Write the full path of the error-handling template created in step 1.

  6. Click Submit Changes to complete the settings.

Figure 14.2 shows the Settings menu options of ColdFusion Administrator.

click to expand
Figure 14.2: The Settings menu of ColdFusion Administrator.

If the requested template isn't available, call a predefined template. You need to specify the path of this predefined template in the Missing Template Handler text box option on the Settings menu page of ColdFusion Administrator.

The following code creates a sample site-wide error template:

 <HTML> <HEAD><TITLE>Sample Site-wide template </TITLE></HEAD> </HTML> <BODY>     An error occurred while accessing this. We have informed the engineer,     please try later. Sorry for the inconvenience.     <!--- Send a mail to the developer notifying the problem and tell him to      correct it-- >     <CFMAIL TO="Developer@organisation.com" from=site-wide@org.net              subject="an error occurred while accessing the page">       Dear developer,       An error occurred while accessing this page. The error information is as       follows.       IP address of the client: #error.remoteaddress#       Date and time of the problem: #error.datetime#       The template that caused the error: #error.template#       Error text: #error.diagnostics# </BODY> </HTML> 




Macromedia ColdFusion MX. Professional Projects
ColdFusion MX Professional Projects
ISBN: 1592000126
EAN: 2147483647
Year: 2002
Pages: 200

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net