Welcome!

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
c:\inetpub\wwwroot\site_error_handler.cfm.

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:

<b>SESSION VARIABLES:</b>
<cfif isdefined("session.cfid")>
<ul>
<cfloop collection="#session#" item="i">
<li>#i#=<cfif issimplevalue(evaluate("session."&i))>#evaluate("session."&i)#
<cfelse>Unprintable Value</cfif>
</cfloop>
</ul>
<cfelse>
None
</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.

Summary
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
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...