You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Toward Better Error Handling - Part

Toward Better Error Handling - Part

Did you know that when a CF error occurs, in many cases not only can you cause something other than the plain, black-on-white default CF error message to appear, but you can also log in a database or e-mail to support staff information about the error, including the error message, date, and time? Maybe you knew about that, but did you know that you can implement a change in this behavior for your entire site?

Did you know you can also easily log or e-mail all the session, application, client, and cookie variables in effect at the time of the error as well as the form fields and URL variables that were passed to the program?

Is all this too good to be true? Is it a dream? Not quite. This solution won't solve all your error handling needs, but it's a vast improvement that's been made even better in Release 4.5.

Introducing Error Handling Templates
In this second part of our series on better error handling we'll explore this new and recently expanded world of using error handling templates. These are CF templates that can better manage both the presentation of errors to the user and the back-end processing of errors for administrative and notification purposes.

They've been around in some form for quite a while, but have changed dramatically in recent releases. And they're no longer the only way to improve error handling.

We now have the choice of controlling this error handling at one of three levels of granularity (see Figure 1):

  1. Site-wide error handling enabled via an Administrator setting
  2. Application-wide error handling enabled using CFERROR
  3. Template, or really tag-specific error handling, using CFTRY and CFCATCH

Here we'll focus on just the first approach, as it can be implemented in a way that has maximum impact on an entire site that hasnt implemented (or not fully implemented) the other choices yet. We'll cover CFERROR in the third installment, then CFTRY/CFCATCH in the final.

The Error Handling Hierarchy
It's useful to think of these three levels of error handling as a hierarchy. In most cases CF handles errors by looking up the hierarchy this way, and resolving an error by applying the error handling mechanism that's closest to the line of code causing the error.

(I realize that many readers don't yet know about - or perhaps don't fully understand - CFERROR and CFTRY, so it may seem premature to discuss it. But without at least some introduction, your first attempts to benefit from site-wide error handling may have some surprises.)

By hierarchy I mean that if a line or segment of code is enclosed with the CFTRY/CFCATCH tags, then any error occurring in that code will be handled by that CFTRY/CFCATCH processing. Such code could log the error, fire off an e-mail, provide a response to the user, or simply ignore the error.

But if there's no CFTRY/CFCATCH surrounding the code in error or if the CFTRY/CFCATCH doesn't trap the error (perhaps it traps only certain types of expected errors), then the error handling process will look for a CFERROR tag to be implemented for the template being executed. As we'll learn in the next article in this series, this is typically set in application.cfm. If there is one, it will handle the error (again, perhaps formatting a more attractive error message or, in some cases, perhaps even being able to fire off e-mail, log the error, etc.).

If there's no CFERROR or the CFERROR is of a type (discussed in Part 3) that fails to trap the error, the error handling process will next look (in Release 4.5 servers) for a site-wide error handling template, if defined in the CF Administrator. we'll see how to define one in a moment.

One reason to be aware of this hierarchy when learning about site-wide error handling is that it's possible some errors wont trigger your site-wide error handling routine. It may be that it's already handled by either a CFTRY surrounding the code or a CFERROR in place at the application level.

Conversely, it's important to note that not all CF errors follow this hierarchical error handling order. Some CF errors wont be caught by the lower-level routines. Compilation errors are an example. They will, however, be handled by the site-wide error handler.

This is another reason to consider the site-wide error handler approach: it nearly guarantees that the user will no longer see the old black-on-white CF error message. Of course, it's a site-wide solution, so it may not be appropriate in all situations. let'ssee how we go about defining a site-wide error handler.

Site-Wide Error Handling
If your site serves just one application or several that are reasonably related to each other, you may want to implement the newest error handling feature introduced in 4.5, called site-wide error handling. This feature will enable a CF template of your own creation to be executed when an error occurs (one that's not been handled already by one of the other error handling templates - remember the hierarchy).

You'll see in the CF Administrator that there's a new option, under the server sections Settings page, called "Site-Wide Error Handler" (see Figure 2).

If you don't see an option to identify a Site-Wide Error Handler (and you're indeed looking at the Server>Settings page in the Administrator), you're probably not running Release 4.5 or greater of ColdFusion. This feature exists only as of that release.

Note that this setting expects a complete physical path to the template, not a Web-server relative path, so if the file is called site_error_handler.cfm and is located in your Webroot directory, c:\inetpub\wwwroot, you would identify it as c:\inetpub\www root\site_error_handler.cfm, not \site_error_handler.cfm or simply error_handler.cfm. It's surprising that Allaire didn't include the usual Browse button found in other Administrator dialogs for naming templates. Perhaps it'll be added in the next release.

Try It Out
There's no better way to learn than by doing. If you have access to a testing server (or your own local workstation has ColdFusion Server installed), why not try out how this site-wide error handling works. we'll start with a very basic template that does nothing more than flag that an error has occurred. ( we'll learn shortly how we can do much more.)

Create a template called site_error_handler.cfm. There's nothing magic about the name. You can use any name for the site-wide error handler, and where you place it is also up to you. It's not important that it be placed in a Web-accessible directory. Just keep in mind where you've placed it.

What you put in for display to the user is entirely up to you. For now, just put in something like this:

<h2>An Error Has Occurred</h2>
It has been trapped by the site-wide error handler in

It may seem needlessly wordy to indicate where the template is that's handling the error, but if you leave this set and forget it (or set it on a testing server where others are affected), it'll be helpful to know why the normal CF error message Isn't showing and how to fix it. we'll leave it like this only momentarily. You may even want to browse whatever template you do create to make sure it appears as youd expect (and make any corrections) before setting it to be the site-wide error handler.

Now, use the Administrator setting shown above to assign this to be your site-wide error handler. (Be careful not to do this on a production server. And if it's on a testing server used by others, you may want to wait until the end of the article to try it after we learn how to display more useful information, such as the error message itself.)

Finally, to test it out, create and execute a template with a ColdFusion error in it. It can be simply a compilation error, such as trying to use the tag <CFIF>, which is obviously incomplete on it's own. This should generate an error that calls up the display not of the normal CF error message but your error handling page.

If the error handler doesn't catch the error, make sure of a few things: Did you apply the change to the Administrator setting? Are you sure the error handling template exists and the path name is correct? If not, there wont be an error when you apply the Administrator setting; instead the following message will display whenever an error (such as our <CFIF> test here) occurs:

Cannot open CFML file

The requested file c:\inetpub\wwroot\ demo\site-wide-error.cfm cannot be found.

In this case, my mistake was in the misspelling of the directory name, wwwroot. The error message indicates I mistakenly left off a "w" in wwwroot. If all seems correct and the error Isn't being caught by the site-wide error handler, make sure there's no CFERROR currently set in the application.cfm of the directory in which your testing code (the code having the sample error) has been placed. If this is the case, move the error testing code to another directory with no CFERROR set for it and try again.

If all still fails, you may want to remove the change in the Administrator identifying the site-wide error handler. As long as it's set but the process Isn't working as expected, you may impact the ability of other developers or users to see expected error messages. Carefully retrace your steps to see why things arent working as expected.

Now that weve confirmed that the site-wide error handler works, let's add more to it. We can choose to display the error message to the user, hide it, or do pretty much anything we want.

Greater Error Handler Capabilities
Indeed, one of the powerful new features of the site-wide error handler (as we'll as some new forms of CFERROR) is that the template can execute all CF tags and functions and has access to all CF variables.

You can now use CFMAIL within the template to send e-mail to support staff or use CFQUERY to store a database record. you're no longer reliant on the user to inform you of the error, and you need not rely on rummaging through CFs error logs to learn of one. You're finally able to know of the error before the user complains about it.

What's more, when you're able to access all the CF tags, functions, and variables, you can choose to display, e-mail, or log information that can greatly increase the ease with which you can diagnose errors. How wonderful it is to finally have access to any CF variables, such as session, cookie, form, and all the other types. we'll learn more about that in a moment. Let's first consider the simple prospect of improving the error message shown to the user.

Improving Error Appearance and Usefulness
Perhaps the most obvious drawback, from your sites perspective of the default CF error message, is it's jarring effect on your Web application interface. It's bad enough that your code has failed (but hey, we all make mistakes). Isn't it a shame, though, that your otherwise colorful and we'll -designed interface is suddenly interrupted by a jarring page with white background and black Times Roman text that screams a less than useful message to your user?

Haven't you wished you could at least show the error message on a page with your sites normal background color and whatever font you use? Perhaps with your company logo and maybe the phone number for your help desk? How about continuing to show the user your navigational toolbars? You can do all this, quite easily in most cases.

Figure 3 shows an error message appearing at half.com, which happens to be a ColdFusion site. I experienced the error recently, and it's clear they're using error handling templates to present an attractive alternative to the standard CF error message.

Notice that the sites normal colors, background, navigational toolbar, and help links are still displayed to the user. Interestingly, theyve chosen not to show the exact CF error message. Whether that's the course you take is up to you. The good news is that you can either show them the error or not, and/or (using the site-wide error handler and some forms of CFERROR) you could send the error in an e-mail to support staff.

The trick to accessing the actual CF error message is in knowing about and using special CF error variables available to such error handling templates.

Error Diagnostic Variables
In our sample, site_error_handler .cfm, as we'll as the half.com example, no details are shown about the error that triggered the error handler. The error itself is indeed available in a variable called #error.diagnostics#, and you can choose what to do with it, if anything.

This variable is only available within error handling templates. It contains the complete text of whatever error has occurred. There are several other variables available as we'll to report the date and time of the error, the template name in error (unless hidden from display by other Administrator options), the query string passed to the page, the page that called the one in error, and even the users IP address and browser (user agent). we'll learn later about the mailto variable and how it works. See the sidebar on error handling variables.

Capturing Other CF Variables
As mentioned before, you may also be able to access all other CF variables, such as session, client, application, form, url, and cookie. These are always available in the site-wide error handler and in newer forms of the application-level error handlers (via CFERROR), discussed next month.

As always, you can show these variables (the error variables or any CF variables) to the user by way of CFOUTPUT. You can also refer to them within a CFMAIL or in a CFQUERY to store data in a database record.

Showing all the variables in effect at the time of an error is a phenomenal capability. How often have you had an error arise and been challenged to determine the reason knowing only the template name? Perhaps the error was caused by form variables passed (or not passed) to the program or session variables, not set as expected.

You may be thinking that a major drawback to this concept is that youd need to know in advance what variables youd want to process and therefore couldnt capture all the variables in effect at the time of the processing of the error handler. More great news: you can!

Looping Through All Variables of a Given Type
You may know that Allaire has been making (in each release) more variables available as CF "structures." Early on, we could process application and session variables this way. As of 4.5, you can also access url, cgi, form, and cookie variables as structures (server variables are still not available, partially for security reasons).

One of the great things about being able to access these variable scopes as structures is that we can use the CFLOOP tag, using it's COLLECTION attribute, to identify the name and value of all variables in a given scope. The following shows an example of one way to loop through all session variables:

<cfif isdefined("session.cfid")>
<cfloop collection="#session#" item="i">
<li>#i#=<cfif issimplevalue(evaluate("session."&i))>#evaluate("session."&i)#
<cfelse>Unprintable Value</cfif>

This first tests if session variables exist for the current user (if so, a session variable called CFID will exist), then loops through each existing session variable, printing it's name and value. If the value is not printable, this is explained. This could occur if the variable is itself a structure or perhaps a query. One way to better handle this problem is to use the custom tag CF_OBJECTDUMP, available free at the Allaire Developers Exchange. It can recursively display structures within structures.

The code example above may be a bit tricky on first viewing, but it works. Putting this sort of code block for each of the available variable scopes would be a great addition to any error handler. Again, whether you choose to display those, send them to support in an e-mail, or store them in a database record is up to you.

Note: While client variables cant be processed as structures, there's a function getclientvariableslist() that can be used to achieve a similar objective. It will return the empty string if there are no client variables.

"Admin E-mail" Address Also Available
In the previous article I mentioned the possibility of defining an e-mail address in the CF Administrator that would be displayed in the default CF error message shown. Users could then click on a link to e-mail that person about the error.

Of course, with the site-wide error handlers ability to send e-mail on it's own, it's not as important to show that sort of mail link to the user, but you may still prefer to use such a global setting to indicate who should receive the error notification.

The good news is that if this admin e-mail value is set in the Administrator, it will be available as an #error.mailto# variable in any site-wide error handler.

Errors in the Error Handler
Finally, those whove been using CF for a while may remember that early forms of error handling templates, namely the CFERROR TYPE="request" and TYPE="validation", didn't allow you to execute CF tags or functions. You could only display the error variables mentioned above with a sort of presumed CFOUTPUT that allowed their use.

The thinking, it was said, was that enabling CF tags and functions (and other variables) in the error handler could raise the dilemma that the error handler could have an error itself, and the system might get stuck in a loop of the error handler trying to process the error handler. It never quite made sense to me (and may have been an apocryphal explanation for the lack of access to tags and functions), as it seemed Allaire could detect an error in the error handler and simply abort the error handling process altogether.

The good news is that this is indeed the tack Allaire takes when using the site-wide error handler. If there's an error in the handler itself, then the user will simply be shown the plain old CF error message in the black on white that were all accustomed to.

There you have it. You should now have a better understanding as we'll as a working version of a site-wide error handling template. You've learned about the hierarchy of error handling mechanisms and how to catch errors that havent been otherwise caught by error handling mechanisms at the template or application levels.

You've learned how to access a host of error diagnostic variables, and perhaps more valuable (for all your coding), you've learned how to loop through the various CF variable scopes to be able to report on all the session variables - or nearly any other scope - in effect at the time of the error. And you've learned what happens when the error handler itself has an error.

For all it's capability, the site-wide error handling capability alone is not the only solution to implement to achieve "better error handling." Due to it's global nature, it may not always be the appropriate (or only) solution. Next month we'll continue the discussion with the next step down the hierarchy: application-level error handling via CFERROR.

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
SYS-CON Events announced today that Technologic Systems Inc., an embedded systems solutions company, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Technologic Systems is an embedded systems company with headquarters in Fountain Hills, Arizona. They have been in business for 32 years, helping more than 8,000 OEM customers and building over a hundred COTS products that have never been discontinued. Technologic Systems’ pr...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
The taxi industry never saw Uber coming. Startups are a threat to incumbents like never before, and a major enabler for startups is that they are instantly “cloud ready.” If innovation moves at the pace of IT, then your company is in trouble. Why? Because your data center will not keep up with frenetic pace AWS, Microsoft and Google are rolling out new capabilities In his session at 20th Cloud Expo, Don Browning, VP of Cloud Architecture at Turner, will posit that disruption is inevitable for c...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor - all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buyers...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Infranics will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Since 2000, Infranics has developed SysMaster Suite, which is required for the stable and efficient management of ICT infrastructure. The ICT management solution developed and provided by Infranics continues to add intelligence to the ICT infrastructure through the IMC (Infra Management Cycle) based on mathemat...
SYS-CON Events announced today that SD Times | BZ Media has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. BZ Media LLC is a high-tech media company that produces technical conferences and expositions, and publishes a magazine, newsletters and websites in the software development, SharePoint, mobile development and commercial UAV markets.
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
"I think that everyone recognizes that for IoT to really realize its full potential and value that it is about creating ecosystems and marketplaces and that no single vendor is able to support what is required," explained Esmeralda Swartz, VP, Marketing Enterprise and Cloud at Ericsson, in this SYS-CON.tv interview at @ThingsExpo, held June 7-9, 2016, at the Javits Center in New York City, NY.
SYS-CON Events announced today that HTBase will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. HTBase (Gartner 2016 Cool Vendor) delivers a Composable IT infrastructure solution architected for agility and increased efficiency. It turns compute, storage, and fabric into fluid pools of resources that are easily composed and re-composed to meet each application’s needs. With HTBase, companies can quickly prov...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, will discuss the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information,