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

Toward Better Error Handling

When your users experience a CF error, do they still see the traditional default - a plain black-on-white CF error screen? More important, are you being notified when such errors occur? Would you like to log the errors to a database? If you're not taking advantage of such capabilities, you should learn about better error handling techniques that are often missed or misunderstood.

In the first two parts of this series (CFDJ, Vol. 2, issues 10 and 12) we learned how to create more effective error handling than the traditional CF default error message. Those articles focused on changes to make in the CF Administrator. In this article we'll focus on implementing error handling choices at the application level.

For those familiar with older forms of application error handling, things have changed dramatically. Many developers still seem unaware of the new capabilities that will dramatically improve your ability to spot and handle errors in your applications.

Site-Wide Error Handling Revisited
Dramatic changes were introduced in ColdFusion release 4.5. Besides what we'll discuss in this article, another new feature in this release was site-wide error handling (discussed in Part 2), which lets you create a new error handling routine that can capture nearly any error occurring in any CF template and process it with complete programmatic control over what should be done with the error.

The benefits are twofold. First, you can format the error to be more attractive, including your own navigational toolbar, color, graphics, font appearance, and more.

Even better, this site-wide error handling routine can perform any ColdFusion tag or function or reference any CF variable, meaning it could send e-mail to the site administrator, store diagnostic information in a database for later analysis, and more. This is a dramatic improvement over what was available prior to release 4.5.

But site-wide error handling, which applies to all applications on a server (site), isn't appropriate if several applications share that single server. Maybe different people should receive e-mail notification of the error, or the data should be stored to different databases, or different applications may want to store different information about errors.

Fortunately, there's an alternative: application-level error handling enabled by the CFERROR tag. But if you think you know about CFERROR, think again. It's also seen a major enhancement in release 4.5.

Older Forms of Error Handling
For those familiar with the CFERROR tag, which has been available since the earliest releases of CF, the news that an error handler can do CFMAIL or database updates may come as a surprise. Until now CFERROR error handling couldn't do either of those things. In fact, error handling templates called by the old form of CFERROR couldn't execute any CF tags at all.

We'll explain CFERROR later for those not familiar with it, but right now I want to clarify for those who did work with it before and were put off by its restrictions, or who indeed wondered why it couldn't be used to automatically send an e-mail when an error occurs, that CFERROR has changed dramatically in release 4.5. New options make it work just like the site-wide error handler described above, including using any CF tag, function, or variable. The change doesn't affect current CFERROR implementations. Instead, it's an opportunity to use the tag in a new form (or maybe drop the older form of CFERROR error handling templates).

Older Forms of Application-Level Error Handling
So what's the CFERROR tag? It's a tag that, like the site-wide error handler feature in the Administrator, lets you describe a template that controls how an error will be displayed and/or handled such that it could present the user with something other than the traditional, simple black-on-white CF error message.

CFERROR TYPE="Request"
The older form of the CFERROR tag had two alternatives, one of which might have appeared:

<CFERROR TYPE="request" TEMPLATE="errorhandler.cfm">
The "type" attribute meant that you wanted to handle any kind of error in your template (or "request"). You'd place this tag in the application.cfm file that controlled your application, so it affected all programs in that application directory (and any templates in subdirectories of that directory if they didn't have their own application.cfm).

It would indicate that if an error arose, ColdFusion would transfer control to the program named in the TEMPLATE attribute. In our example, we named it "errorhandler.cfm", but you could have given it any name you chose. With control passed to this template, it could be formatted to your preference using any HTML tags to describe the appearance, color, font, and layout of your choosing.

As mentioned, however, this older form of CFERROR (type="request") wasn't allowed to use any ColdFusion tags, functions, or any of the variables you might like to see, including session, URL, form, and cookie. This also meant you couldn't leverage any previously written code using CFINCLUDE, which meant you had to hard-code any headers, footers, or navigational toolbars you might want to present to the user. And, of course, you couldn't do a CFMAIL, CFQUERY, or any other tag.

You may wonder why this was at all useful, and in fact many people felt the same way and never bothered with it. It did have one means to be a little more useful. As I discussed in the last installment on site-wide error handlers, ColdFusion exposes a set of "error variables" for use in any error handling templates, including that pointed to by CFERROR. They include:

  • Error.DateTime: Date and time of the error
  • Error.Template: Template in which the error occurred
  • Error.Diagnostics: Actual CF error message
  • Error.HTTPReferer: The page that called the template getting the error
  • Error.QueryString: The URL string, if any, passed after the name of the template (the raw format of any "URL" variables available to the page)
  • Error.Browser: Type of browser calling the page in error
  • Error.RemoteAddress: IP address of the user calling the page in error
  • Error.MailTo: Mailing address designated to receive e-mails sent by the user choosing to respond to the error message
The page could be formatted to display those variables. If you think about it, though, how could you output such variables if you can't use a CFOUTPUT? Well, Allaire got around that by letting you specify those variables surrounded by just pound signs and with no CFOUTPUT needed. You still couldn't refer to any other variables, though.

It was a step above the traditional, plain CF error message, because it could have a more consistent look and feel with the rest of your application, but it was of marginal use in creating a complete error handling mechanism. What developers really wanted was a means to be notified when an error arose.

The Misunderstood MAILTO Attribute
Many developers interested in the capability of receiving an e-mail notification about an error were excited to see the CFERROR tag supported a MAILTO attribute. You could write the tag as:

<CFERROR TYPE="request" TEMPLATE="errorhandler.cfm" MAILTO="[email protected]">
Sadly, it didn't accomplish what most were expecting. The Allaire forums are littered with folks lamenting that "CFERROR's not working. I'm not getting any e-mail, and indeed the mail message is just being displayed to the user when an error occurs."

Their mistake was that they expected this attribute to cause an error to be sent automatically to the named administrator. Instead, it simply populated the Error.Mailto variable mentioned in the previous section.

So why was the e-mail just being displayed on the screen? Well, think about it: error handlers aren't allowed to use (and won't execute) any CF tags or regular CF variables. If an error handler mistakenly tried to do a CF-MAIL, CF would ignore it and simply pass it and the mail message between the tags to the user as HTML. Of course, a browser doesn't know what to do with a CFMAIL tag either, so the user simply saw the mail message displayed to them. Not what was expected at all!

The real intent of the MAILTO variable was to display, as part of the error message you formatted, a hyperlink the user could click on to send an e-mail to the named address (using the mailto: protocol, as in <href="mailto:#error.mailto#">Please notify the administrator of this error</a>).

Of course, you had to hope they'd bother to take that link and that they'd be willing to copy and paste the error on the browser screen into the e-mail. Even then, this e-mail couldn't really capture everything you needed to know about the error, since you didn't have access to all the CF variables in play at the time of the error (form, session, local, etc.).

Circumventing the Limitations: Old Tricks
Getting notification about the error is of course a critical need. The MAILTO attribute alone and presenting a mailto hyperlink to the user just didn't cut it. Clever CF programmers realized there were several ways to get around the e-mail limitation.

One approach was to create a form in the error handler template in which you stored all the error variables in hidden fields on the form. The user would be asked to submit the form, passing control to a real CF template, which could then send an e-mail or create some sort of error database log entry.

A natural extension of that, for those with JavaScript skills, was to simply have that form submitted automatically by way of a JavaScript submit() method. An example of this is presented in the Allaire Forums at http://forums. allaire.com/devconf/Thread.cfm?&&MessageID= 178597&#Message 308262.

Fortunately, the newer form of CFERROR can get around the need to play those games and also provides a lot more about the state of the program at the time of the error. Now you can simply do a CFMAIL and much more in the error handler itself. Before we get to that, let's look at the other of the two older forms of CFERROR processing.

CFERROR TYPE="Validation"
There were actually two older forms of CFERROR, the other being TYPE="Validation". This feature worked (and still does) much the same as TYPE="Request". If you created a form that used the "hidden field" validation enabled by ColdFusion (_required, _date, _integer, etc.), this form of CFERROR could name another template that could lay out the appearance of the messages shown when a user's input failed to meet the validation. There are three special "error" variables for this handler:

  • Error.InvalidFields: Detailed validation error messages
  • Error.ValidationHeader: The wording that normally appeared at the top of such a form validation error message display
  • Error.ValidationFooter: The wording that normally appeared at the bottom of such a form validation error message display
Each of these older forms of CFERROR, while interesting and useful in at least providing a more consistent interface when errors arose, was limited and not at all capable of providing you, as administrator of the application, with an e-mail to know that an error had occurred, let alone a means to store a database to track such errors.

Newer Forms of Application-Level Error Handling
Allaire realized that people wanted an error handler to do more. So they added new features in release 4.0 (CFTRY/CFCATCH) and release 4.5 in the form of site-wide error handling and two new types of CFERROR handling, each of which have complete access to all CF tags, functions, and variables. Finally, we're able to create full-powered error handlers.

A Brand New CFERROR TYPE="Exception"
The first new form is TYPE="Exception". On a simple level this is just a new "type" of CFERROR error handler, and the format could be specified as:

<CFERROR TYPE="Exception" TEMPLATE="enhanced_errorhandler.cfm">
Since this template, which we've called enhanced_errorhandler.cfm, can do any tags, functions, or variables, we can have it do a CFMAIL (using the MAILTO attribute, if specified, or any other CF variable or hard-coded value) or a CFQUERY to insert a log database record, and more.

The ability to access any variables shouldn't be underestimated. You can now take note of the session, application, client, cookie, cgi, form, URL, and other variables in play at the time of the error. This makes a tremendous difference in being able to diagnose the cause of an error. In Part 2 of this series, "Site-Wide Error Handling," I offered some code samples to allow you to loop through all the variables in each of these scopes. Wonder how you can have access to the form and URL variables? If a CFERROR transfers control to the error handler, doesn't that lose the form and URL variables? Nope. It appears to work more like a CFINCLUDE, so those variables are there if they were passed to the page that had the error.

More on the Error Handling Hierarchy
Note that you can certainly have both the old and new forms of CFERROR in the form of two different tags in the application.cfm. There's no significance to the order in which they're specified. The real significance is that the "request" handler, if specified, will handle any errors the "exception" handler doesn't.

When would it step in? How about if there's an error in the "exception" handler? This often happens when people are getting started. If they have an error in the "exception" handler, control passes to the older style "request" handler and no automatic e-mail or database log is created. The problem is simply an error in the handler, but it's hard to diagnose at first, especially if the output to the screen for the two error handlers is the same.

What if there's no "request" handler when an error occurs in the "exception" error handler? Then CF will look for a site-wide error handler, and if there's none, the old-style, plain CF error message will be displayed.

Speaking of the hierarchy, it's more accurate to say that the exception handler will handle an exception that hasn't otherwise been handled. As we'll learn in the next installment, you can handle errors at an even finer level of control, within a piece of program code, with the CFTRY/CFCATCH tags.

The Curious Type="Monitor"
I mentioned earlier that there were two new types of CFERROR mechanisms. The second is Type="Monitor". It's one that's often misunderstood and seems relatively poorly documented. It's like the new "exception" type in its power to use any tags, functions, or variables. So what's the difference? It's a subtle one, and it will make a lot more sense if we wait until after we learn about CFTRY/CFCATCH and exception types in the final installment.

Problems Using the New Error Handlers
Beware the documentation and old articles, forum notes, and so on.

The first thing to be aware of as you try to learn more about these new forms of error handlers is that many resources you look to may have dated or incomplete information. They're still relatively new, and the resource (Allaire forums, articles, and so on) may be referring to what was true when that resource was created.

Even then you may find that conversations with other developers lead to a variety of explanations of what can and can't be done. I don't claim to have written the authoritative explanation (far from it), but I still hear from otherwise guru-level people who don't quite get all the subtleties of these new forms of error handling.

Indeed, even the Allaire documentation shows occasional lapses that suggest they've only been updated to mention the new features. The problem is that some comments remain that are relevant only to the "old style" of CFERROR processing. For instance, the CFERROR usage topic in the reference manual states:

"To help ensure that error pages display successfully, pages you specify with CFERROR should not be encoded with the cfencode utility."

This was true for the older style CFERROR types; while they were .cfms, they weren't processed as such, so an encoded file wouldn't display properly to the user. It's not an issue at all for the two newer types of error handlers (or indeed the site-wide handler). It's not that big a deal, but it's reflective of a concern you should have about the details you may read about on this subject.

Problems Using Code in Earlier Versions
It's important to keep in mind that not only do these two new CFERROR types (exception and monitor) work only in 4.5 or beyond, they'll also specifically fail if used in an older release. It's not enough to test for the version (using the variable Server.Coldfusion.ProductVersion) and execute the code only if running in 4.5. If the version is not 4.5 or above, and you try to use, for instance, CFERROR TYPE = "exception," you'll get a compilation error.

What if you have to move code back and forth between a server that's 4.5 or greater and one that's not? Here's a trick:

<CFSET Version= ListGetAt(Server.ColdFusion.ProductVersion,1, ", ") & "." & ListGetAt(Server.ColdFusion.ProductVersion,2, ", ")>

<CFIF Version GE 4.5> <CFSET Type="Exception"> <CFERROR Template="error_handler_for_exception_type.cfm" Type="#type#"> </CFIF>

Handling 404 Errors
It's also important to note that these error handlers can't capture "404 (file not found)" errors caused when a user types in a URL for a file that doesn't exist. If the file they're requesting is a .cfm file, there's a solution: a new "missing template handler" in the admin, which allows you to customize the error appearance. If the file they're requesting is an .htm or other file, you'll need to set up your Web server to handle such missing files.

Summary
There you have it. I hope this quick tour of application-level error handling has been informative and proves useful. With this knowledge, no site or application should ever again show the user the plain black-on-white error message!

The final installment of this series will examine the CFTRY and CFCATCH approach to error handling. We'll show some capabilities enabled by that, such as detecting and resolving database errors in a more well-planned manner. "Code-level" error handling gives you a finer level of control than application-level error handling. Until then, you can learn more in the Allaire docs as well as in CFDJ articles, such as "What's In It for Me? Taking Advantage of New Features in ColdFusion 4.0," by Michael J. Murdy at http://www.sys-con.com/coldfusion/article.cfm?id=20.

Finally, there are several other topics on using CFERROR that we've run out of time to cover. You can see an extended discussion on my Web site at http://www.systemanage.com/cff/articles.cfm.

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
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, 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. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, 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. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
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 CAST Software 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
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/.
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 SourceForge has been named “Media Sponsor” of 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. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
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 Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
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...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. 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.