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="admin@youhost.com">
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
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that Elastifile 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. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
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, will introduce 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...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
In his session at @ThingsExpo, Sudarshan Krishnamurthi, a Senior Manager, Business Strategy, at Cisco Systems, discussed how IT and operational technology (OT) work together, as opposed to being in separate siloes as once was traditional. Attendees learned how to fully leverage the power of IoT in their organization by bringing the two sides together and bridging the communication gap. He also looked at what good leadership must entail in order to accomplish this, and how IT managers can be the ...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
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. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...