CPCUG Monitor
Creating dynamic websites with ColdFusion
Part 6: Error handling
by Michael Smith
What is ColdFusion?
In this article we continue to look at what ColdFusion is
and how you can use it for dynamic website creation. We cover error handling
and dealing with 404 errors in ColdFusion. Error handling is important to both
make your site more professional and for security reasons.
In case you missed previous articles that introduced
ColdFusion, let me explain what it is. ColdFusion is a programming language
based on standard HTML (Hyper Text Markup Language) that is used to write
dynamic webpages. It lets you create pages on the fly that differ depending on
user input, database lookups, time of day or what ever other criteria you dream
up! ColdFusion pages consist of standard HTML tags such as <FONT
SIZE="+2"> together with CFML
(ColdFusion Markup Language) tags such as <CFSEARCH>, <CFIF>
and <CFLOOP>.
ColdFusion was introduced by Allaire in 1996 and is currently on version 4.
Error handling
Cfcatch/cftry
CFERROR Error page
with js
Administrator settings
Email
Log file
Hacker notes
Tree in the forrest
Syntax checker,
Application.cfm and onpageend.cfm?
Cferror
Error.Diagnostics
Detailed
error diagnostics from ColdFusion Server.
Error.MailTo
Email
address of administrator who should be notified (corresponds to the value set
in the MAILTO attribute of CFERROR).
Error.DateTime
Date
and time when the error occurred.
Error.Browser
Browser
that was running when the error occurred.
Error.RemoteAddress
IP
address of the remote client.
Error.HTTPReferer
Page
from which the client accessed the link to the page where the error occurred.
Error.Template
Page
being executed when the error occurred.
Error.QueryString
URL
query string of the client's request.
Structured Exception Handling
The ColdFusion Server offers a means for developers to catch
and process exceptions in ColdFusion application pages, through the CFTRY, CFCATCH,
and CFTHROW tags.
Contents
·
Overview
of Exception Handling in ColdFusion
·
Exception-Handling
Strategies
·
Exception
Handling Example
·
Exception Information in CFCATCH
Overview of Exception Handling in ColdFusion
Used with one or more CFCATCH tags, the CFTRY tag allows
developers to catch and process exceptions in ColdFusion pages. Exceptions
include any event that disrupts the normal flow of instructions in a ColdFusion
page, such as failed database operations, missing include files, or
developer-specified events.
You use the following syntax for CFTRY/CFCATCH blocks:
<CFTRY>
... Add code here ...
<CFCATCH
TYPE="exception type">
... Add
exception processing code here ...
</CFCATCH>
... Additional
CFCATCH blocks go here ...
</CFTRY>
In order for ColdFusion to handle an exception, it must
appear within a CFTRY block. You might enclose an entire application page in a
CFTRY block, using a CFCATCH block around a potential error.
To catch errors in a single problematic SQL statement, for
example, you might narrow the focus by using a CFTRY block with a CFCATCH
TYPE="Database" tag, outputting the CFCATCH.State information as
well.
See the CFML Language Reference for information on the CFTRY,
CFCATCH, and CFTHROW tags.
Types of recoverable exceptions supported
The ColdFusion Server supports several types of recoverable
exceptions. Use the TYPE attribute in the CFCATCH tag to determine which type
of exception to catch.
Application-defined exception events
ColdFusion applications can raise exceptions using the
CFTHROW tag, with an optional diagnostic message. CFTHROW raises an exception
that can be caught by a CFCATCH TYPE="Application" tag, or a CFCATCH
TYPE="Any" tag. This exception can also be caught by a CFCATCH block
that has no TYPE attribute.
Database failures
Use the CFCATCH tag with TYPE="Database" or
CFCATCH TYPE="Any" to catch failed database operations, such as
failed SQL statements, ODBC problems, and so on.
Template errors
Use the CFCATCH tag with TYPE="Template" or
TYPE="Any" to catch general application page errors.
Missing included file errors
Use the CFCATCH tag with TYPE="MissingInclude" or
TYPE="Any" to catch errors for missing included files.
Object exceptions
Use the CFCATCH TYPE="Object" tag to catch
exceptions in ColdFusion code that works with objects.
Security exceptions
Use the CFCATCH TYPE="Security" tag to raise
catchable exceptions in ColdFusion code that works with security.
Expression exceptions
Use the CFCATCH TYPE="Expression" tag to catch
exceptions when an expression fails evaluation.
Locking exceptions
Use the CFCATCH tag with TYPE="Lock" to catch
failed locking operations, such as when a CFLOCK critical section times out or
fails at runtime.
Unexpected internal exceptions
You can catch unexpected exceptions in the ColdFusion Server
with the CFCATCH TYPE="Any" tag.
Note
Attempting to handle unexpected exceptions in CFML code can
cause unpredictable results, and may seriously degrade or crash the ColdFusion
Server.
Exception-Handling Strategies
Developers can use CFTRY with CFCATCH to handle exceptions
based on their point of origin within an application page, or based on
diagnostic information.
Handling exceptions based on point of origin
Use the CFTRY tag with one or more CFCATCH blocks to define
a ColdFusion block for exception handling. When an application page raises an
error condition, the ColdFusion server checks the stack of currently active
blocks for a corresponding CFCATCH handler. At extremes, an exception-prone tag
might be enclosed in a specialized combination of CFTRY and CFCATCH to
immediately isolate the tag's exceptions, or to use CFTRY with CFCATCH
TYPE="Any" at a main processing level to gracefully terminate a
subsystem's processing in case of an unexpected error.
Handling exceptions based on diagnostic information
Use CFCATCH with the attribute TYPE="exception type"
to catch specific types of exceptions. A CFCATCH handler can further analyze
the exception's diagnostic information, and re-throw the exception if the
exceptional condition requires further handling.
Exception Handling Example
The following example shows CFTRY and CFCATCH, using a
sample data source called company and a sample included file, includeme.cfm.
If the data access driver raises an exception during the
CFQUERY statement's execution, the application page flow continues to the
CFCATCH TYPE="Database" exception handler. It then resumes with the
next statement after the CFTRY block, once the CFCATCH TYPE="Database"
handler completes.
Similarly, the CFCATCH TYPE="MissingInclude" block
handles exceptions raised by the CFINCLUDE tag. Any unknown, but possibly
recoverable, exceptions are handled by the CFCATCH TYPE="Any" block.
<!--- Wrap code you want to check in
a CFTRY block --->
<CFTRY>
<CFQUERY
NAME="test" DATASOURCE="company">
SELECT
DepartmentID, FirstName, LastName
FROM
employees
WHERE
employeeID=#val(EmpID)#
</CFQUERY>
<HTML>
<HEAD>
<TITLE>Test CFTRY/CFCATCH</TITLE>
</HEAD>
<BODY>
<HR>
<CFINCLUDE
TEMPLATE="includeme.cfm">
<CFOUTPUT
QUERY="test">
<P>Department: #DepartmentID#
<P>Last
Name: #LastName#
<P>First
Name: #FirstName#
</CFOUTPUT>
<HR>
<!--- Use CFCATCH to test for missing
included files.
Print Message and Detail error messages. --->
<CFCATCH
TYPE="MissingInclude">
<H1>Missing Include File</H1>
<CFOUTPUT>
<UL>
<LI><b>Message:</b> #CFCATCH.Message#
<LI><b>Detail:</b> #CFCATCH.Detail#
<LI><b>File name:</b> #CFCATCH.MissingFilename#
</UL>
</CFOUTPUT>
</CFCATCH>
<!--- Use CFCATCH to test for
database errors.
Print error messages. --->
<CFCATCH
TYPE="Database">
<H1>Database Error</H1>
<CFOUTPUT>
<UL>
<LI><b>Message:</b> #CFCATCH.Message#
<LI><b>Native error code:</b>
#CFCATCH.NativeErrorCode#
<LI><b>SQLState:</b> #CFCATCH.SQLState#
<LI><b>Detail:</b> #CFCATCH.Detail#
</UL>
</CFOUTPUT>
</CFCATCH>
<!--- Use CFCATCH with
TYPE="Any"
to find unexpected exceptions. --->
<CFCATCH TYPE="Any">
<H1>Other Error: #CFCATCH.Type#</H1>
<CFOUTPUT>
<UL>
<LI><b>Message:</b> #CFCATCH.message#
<LI><b>Detail:</b> #CFCATCH.Detail#
</UL>
</CFOUTPUT>
</CFCATCH>
</CFTRY>
</BODY>
</HTML>
CFTHROW syntax
Use CFTHROW within a CFTRY block to raise an error
condition. The CFCATCH block can access this message through CFCATCH.message.
<CFTHROW MESSAGE="...diagnostic
message...">
This form of the CFTHROW tag throws a new CFML-recoverable
exception with the specified diagnostic message.
Using CFTHROW without the MESSAGE attribute throws a new
CFML-recoverable exception with an empty diagnostic message.
CFTRY syntax
The CFTRY tag starts a ColdFusion exception-handling block.
One or more CFCATCH tags must be included within a CFTRY block.
<CFTRY>
...Other CFML tags...
<CFCATCH TYPE="Any">
</CFTRY>
Note
A CFCATCH block must be the last set of tags within a CFTRY
block.
CFCATCH syntax
The CFCATCH tag catches exceptions of the type specified in
the TYPE attribute, such as database, application, missing include, or
application page.
<CFCATCH TYPE="exception type">
The following form of the CFCATCH tag catches all CFML-recoverable
exceptions generated within the preceding CFTRY block, or within any of the
CFTRY block's children.
<CFCATCH TYPE="Any">
A CFCATCH tag without a TYPE attribute is equivalent to
CFCATCH TYPE="Any".
Order of evaluation
For a given CFTRY block, CFCATCH tags are tested in the
order in which they appear in the application page.
Note
An exception raised within a CFCATCH block cannot be handled
by the CFTRY block that immediately encloses the CFCATCH tag.
See the CFML Language Reference for information on the
syntax of the exception handling tags, CFTRY, CFCATCH, and CFTHROW.
Exception Information in CFCATCH
Within a CFCATCH block, the active exception's properties
can be accessed as variables:
CFCATCH.TYPE -- The exception's type,
returned as a string:
·
Application
·
Database
·
Template
·
MissingInclude
·
Object
·
Security
·
Expression
·
Lock
·
Any
CFCATCH.MESSAGE -- The exception's
diagnostic message, if one was provided. If no diagnostic message is available,
this is an empty string.
CFCATCH.DETAIL -- A detailed message from
the CFML interpreter. This message, which contains HTML formatting, can help to
determine which tag threw the exception.
Database exceptions
For database exceptions, ColdFusion supplies some additional
diagnostic information. The following variables are available whenever the
exception type is database:
CFCATCH.NATIVEERRORCODE -- The native error
code associated with this exception. Database drivers typically provide error codes
to assist in the diagnosis of failing database operations. The values assumed
by CFCATCH.NATIVEERRORCODE are driver-dependent. If no error code is provided,
the value of NativeErrorCode is -1.
CFCATCH.SQLSTATE -- The SQLSTATE code
associated with this exception. Database drivers typically provide error codes
to assist in the diagnosis of failing database operations. The values assumed
by CFCATCH.SQLSTATE are driver-dependent. If no SQLSTATE value was provided,
the value of SQLSTATE is -1.
Locking exceptions
For exceptions related to CFLOCK sections, there is
additional information available within the CFCATCH block:
CFCATCH.LOCKNAME -- The name of the
affected lock. This is set to "anonymous" if the lock name is not
known.
CFCATCH.LOCKOPERATION -- The operation that
failed. This is set to "unknown" if the failed operation is unknown.
MissingInclude exceptions
For exceptions related to missing files, where the type of
exception is MissingInclude, the following variable is available:
CFCATCH.MISSINGFILENAME -- The name of the
file missing in an exception of type MissingInclude.
Summary
In this article we learned how to index both documents and
large database queries for free text searches using Verity. We used the CFINDEX
and CFSEARCH tags together with a CFOUTPUT to display results
To Learn More
You can download a free 30 day-evaluation version of
ColdFusion from Allaire or request a free eval CD-ROM from
the Allaire website http://www.allaire.com/
Allaire Corporation
1 Alewife Center
Cambridge, MA 02140
Tel: 617.761.2000 voice
Fax: 617.761.2001 fax
Toll Free: 888.939.2545
Email: [email protected]
Web: www.allaire.com
ColdFusion Resources
Allaire also maintains an extensive knowledge base and
tech support forums on their website.
CPCUG and TeraTech ColdFusion Conference http://www.cfconf.org/
TeraTech maintains a ColdFusion code cuttings called
ColdCuts at http://www.teratech.com/ColdCuts/.
This page also has links to about a dozen ColdFusion white papers in the CF
Info Center.
The Maryland ColdFusion User Group meets the second
Tuesday of each month at Backstreets Cafe, 12352 Wilkins Avenue, Rockville. See http://www.cfug-md.org/ for details and
directions.
The DC ColdFusion User Group meets the first Wednesday
each month at Figleaf , 16th and P St NW, Washington DC. See the
DCCFUG page on http://www.figleaf.com/
for details and directions.
Bio
Michael Smith is president of TeraTech, a ten year old
Rockville Maryland based consulting company that specializes in ColdFusion,
Database and Visual Basic development. You can reach Michael at [email protected] or 301-424-3903.