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
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, 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.
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at Dell EMC, introduced a methodology for capturing, enriching and sharing data (and analytics) across the organization...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Analytic. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software in the hope of capturing value in IoT. Although IoT is relatively new in the market, it has already gone through many promotional terms such as IoE, IoX, SDX, Edge/Fog, Mist Compute, etc. Ultimately, irrespective of the name, it is about deriving value from independent software assets participating in an ecosystem as one comprehensive solution.
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
NHK, Japan Broadcasting, will feature the upcoming @ThingsExpo Silicon Valley in a special 'Internet of Things' and smart technology documentary that will be filmed on the expo floor between November 3 to 5, 2015, in Santa Clara. NHK is the sole public TV network in Japan equivalent to the BBC in the UK and the largest in Asia with many award-winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology and will be covering @ThingsExpo Silicon Val...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Judith Hurwitz is president and CEO of Hurwitz & Associates, a Needham, Mass., research and consulting firm focused on emerging technology, including big data, cognitive computing and governance. She is co-author of the book Cognitive Computing and Big Data Analytics, published in 2015. Her Cloud Expo session, "What Is the Business Imperative for Cognitive Computing?" is scheduled for Wednesday, June 8, at 8:40 a.m. In it, she puts cognitive computing into perspective with its value to the busin...
NHK, Japan Broadcasting, will feature the upcoming @ThingsExpo Silicon Valley in a special 'Internet of Things' and smart technology documentary that will be filmed on the expo floor between November 3 to 5, 2015, in Santa Clara. NHK is the sole public TV network in Japan equivalent to the BBC in the UK and the largest in Asia with many award-winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology and will be covering @ThingsExpo Silicon Val...
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...