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
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
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.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
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, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, 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 buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, 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.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix 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. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...