Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Toward Better Error Handling - Part

Toward Better Error Handling - Part

Did you know that when a CF error occurs, in many cases not only can you cause something other than the plain, black-on-white default CF error message to appear, but you can also log in a database or e-mail to support staff information about the error, including the error message, date, and time? Maybe you knew about that, but did you know that you can implement a change in this behavior for your entire site?

Did you know you can also easily log or e-mail all the session, application, client, and cookie variables in effect at the time of the error as well as the form fields and URL variables that were passed to the program?

Is all this too good to be true? Is it a dream? Not quite. This solution won't solve all your error handling needs, but it's a vast improvement that's been made even better in Release 4.5.

Introducing Error Handling Templates
In this second part of our series on better error handling we'll explore this new and recently expanded world of using error handling templates. These are CF templates that can better manage both the presentation of errors to the user and the back-end processing of errors for administrative and notification purposes.

They've been around in some form for quite a while, but have changed dramatically in recent releases. And they're no longer the only way to improve error handling.

We now have the choice of controlling this error handling at one of three levels of granularity (see Figure 1):

  1. Site-wide error handling enabled via an Administrator setting
  2. Application-wide error handling enabled using CFERROR
  3. Template, or really tag-specific error handling, using CFTRY and CFCATCH

Here we'll focus on just the first approach, as it can be implemented in a way that has maximum impact on an entire site that hasnt implemented (or not fully implemented) the other choices yet. We'll cover CFERROR in the third installment, then CFTRY/CFCATCH in the final.

The Error Handling Hierarchy
It's useful to think of these three levels of error handling as a hierarchy. In most cases CF handles errors by looking up the hierarchy this way, and resolving an error by applying the error handling mechanism that's closest to the line of code causing the error.

(I realize that many readers don't yet know about - or perhaps don't fully understand - CFERROR and CFTRY, so it may seem premature to discuss it. But without at least some introduction, your first attempts to benefit from site-wide error handling may have some surprises.)

By hierarchy I mean that if a line or segment of code is enclosed with the CFTRY/CFCATCH tags, then any error occurring in that code will be handled by that CFTRY/CFCATCH processing. Such code could log the error, fire off an e-mail, provide a response to the user, or simply ignore the error.

But if there's no CFTRY/CFCATCH surrounding the code in error or if the CFTRY/CFCATCH doesn't trap the error (perhaps it traps only certain types of expected errors), then the error handling process will look for a CFERROR tag to be implemented for the template being executed. As we'll learn in the next article in this series, this is typically set in application.cfm. If there is one, it will handle the error (again, perhaps formatting a more attractive error message or, in some cases, perhaps even being able to fire off e-mail, log the error, etc.).

If there's no CFERROR or the CFERROR is of a type (discussed in Part 3) that fails to trap the error, the error handling process will next look (in Release 4.5 servers) for a site-wide error handling template, if defined in the CF Administrator. we'll see how to define one in a moment.

One reason to be aware of this hierarchy when learning about site-wide error handling is that it's possible some errors wont trigger your site-wide error handling routine. It may be that it's already handled by either a CFTRY surrounding the code or a CFERROR in place at the application level.

Conversely, it's important to note that not all CF errors follow this hierarchical error handling order. Some CF errors wont be caught by the lower-level routines. Compilation errors are an example. They will, however, be handled by the site-wide error handler.

This is another reason to consider the site-wide error handler approach: it nearly guarantees that the user will no longer see the old black-on-white CF error message. Of course, it's a site-wide solution, so it may not be appropriate in all situations. let'ssee how we go about defining a site-wide error handler.

Site-Wide Error Handling
If your site serves just one application or several that are reasonably related to each other, you may want to implement the newest error handling feature introduced in 4.5, called site-wide error handling. This feature will enable a CF template of your own creation to be executed when an error occurs (one that's not been handled already by one of the other error handling templates - remember the hierarchy).

You'll see in the CF Administrator that there's a new option, under the server sections Settings page, called "Site-Wide Error Handler" (see Figure 2).

If you don't see an option to identify a Site-Wide Error Handler (and you're indeed looking at the Server>Settings page in the Administrator), you're probably not running Release 4.5 or greater of ColdFusion. This feature exists only as of that release.

Note that this setting expects a complete physical path to the template, not a Web-server relative path, so if the file is called site_error_handler.cfm and is located in your Webroot directory, c:\inetpub\wwwroot, you would identify it as c:\inetpub\www root\site_error_handler.cfm, not \site_error_handler.cfm or simply error_handler.cfm. It's surprising that Allaire didn't include the usual Browse button found in other Administrator dialogs for naming templates. Perhaps it'll be added in the next release.

Try It Out
There's no better way to learn than by doing. If you have access to a testing server (or your own local workstation has ColdFusion Server installed), why not try out how this site-wide error handling works. we'll start with a very basic template that does nothing more than flag that an error has occurred. ( we'll learn shortly how we can do much more.)

Create a template called site_error_handler.cfm. There's nothing magic about the name. You can use any name for the site-wide error handler, and where you place it is also up to you. It's not important that it be placed in a Web-accessible directory. Just keep in mind where you've placed it.

What you put in for display to the user is entirely up to you. For now, just put in something like this:

<h2>An Error Has Occurred</h2>
It has been trapped by the site-wide error handler in
c:\inetpub\wwwroot\site_error_handler.cfm.

It may seem needlessly wordy to indicate where the template is that's handling the error, but if you leave this set and forget it (or set it on a testing server where others are affected), it'll be helpful to know why the normal CF error message Isn't showing and how to fix it. we'll leave it like this only momentarily. You may even want to browse whatever template you do create to make sure it appears as youd expect (and make any corrections) before setting it to be the site-wide error handler.

Now, use the Administrator setting shown above to assign this to be your site-wide error handler. (Be careful not to do this on a production server. And if it's on a testing server used by others, you may want to wait until the end of the article to try it after we learn how to display more useful information, such as the error message itself.)

Finally, to test it out, create and execute a template with a ColdFusion error in it. It can be simply a compilation error, such as trying to use the tag <CFIF>, which is obviously incomplete on it's own. This should generate an error that calls up the display not of the normal CF error message but your error handling page.

If the error handler doesn't catch the error, make sure of a few things: Did you apply the change to the Administrator setting? Are you sure the error handling template exists and the path name is correct? If not, there wont be an error when you apply the Administrator setting; instead the following message will display whenever an error (such as our <CFIF> test here) occurs:

Cannot open CFML file

The requested file c:\inetpub\wwroot\ demo\site-wide-error.cfm cannot be found.

In this case, my mistake was in the misspelling of the directory name, wwwroot. The error message indicates I mistakenly left off a "w" in wwwroot. If all seems correct and the error Isn't being caught by the site-wide error handler, make sure there's no CFERROR currently set in the application.cfm of the directory in which your testing code (the code having the sample error) has been placed. If this is the case, move the error testing code to another directory with no CFERROR set for it and try again.

If all still fails, you may want to remove the change in the Administrator identifying the site-wide error handler. As long as it's set but the process Isn't working as expected, you may impact the ability of other developers or users to see expected error messages. Carefully retrace your steps to see why things arent working as expected.

Now that weve confirmed that the site-wide error handler works, let's add more to it. We can choose to display the error message to the user, hide it, or do pretty much anything we want.

Greater Error Handler Capabilities
Indeed, one of the powerful new features of the site-wide error handler (as we'll as some new forms of CFERROR) is that the template can execute all CF tags and functions and has access to all CF variables.

You can now use CFMAIL within the template to send e-mail to support staff or use CFQUERY to store a database record. you're no longer reliant on the user to inform you of the error, and you need not rely on rummaging through CFs error logs to learn of one. You're finally able to know of the error before the user complains about it.

What's more, when you're able to access all the CF tags, functions, and variables, you can choose to display, e-mail, or log information that can greatly increase the ease with which you can diagnose errors. How wonderful it is to finally have access to any CF variables, such as session, cookie, form, and all the other types. we'll learn more about that in a moment. Let's first consider the simple prospect of improving the error message shown to the user.

Improving Error Appearance and Usefulness
Perhaps the most obvious drawback, from your sites perspective of the default CF error message, is it's jarring effect on your Web application interface. It's bad enough that your code has failed (but hey, we all make mistakes). Isn't it a shame, though, that your otherwise colorful and we'll -designed interface is suddenly interrupted by a jarring page with white background and black Times Roman text that screams a less than useful message to your user?

Haven't you wished you could at least show the error message on a page with your sites normal background color and whatever font you use? Perhaps with your company logo and maybe the phone number for your help desk? How about continuing to show the user your navigational toolbars? You can do all this, quite easily in most cases.

Figure 3 shows an error message appearing at half.com, which happens to be a ColdFusion site. I experienced the error recently, and it's clear they're using error handling templates to present an attractive alternative to the standard CF error message.

Notice that the sites normal colors, background, navigational toolbar, and help links are still displayed to the user. Interestingly, theyve chosen not to show the exact CF error message. Whether that's the course you take is up to you. The good news is that you can either show them the error or not, and/or (using the site-wide error handler and some forms of CFERROR) you could send the error in an e-mail to support staff.

The trick to accessing the actual CF error message is in knowing about and using special CF error variables available to such error handling templates.

Error Diagnostic Variables
In our sample, site_error_handler .cfm, as we'll as the half.com example, no details are shown about the error that triggered the error handler. The error itself is indeed available in a variable called #error.diagnostics#, and you can choose what to do with it, if anything.

This variable is only available within error handling templates. It contains the complete text of whatever error has occurred. There are several other variables available as we'll to report the date and time of the error, the template name in error (unless hidden from display by other Administrator options), the query string passed to the page, the page that called the one in error, and even the users IP address and browser (user agent). we'll learn later about the mailto variable and how it works. See the sidebar on error handling variables.

Capturing Other CF Variables
As mentioned before, you may also be able to access all other CF variables, such as session, client, application, form, url, and cookie. These are always available in the site-wide error handler and in newer forms of the application-level error handlers (via CFERROR), discussed next month.

As always, you can show these variables (the error variables or any CF variables) to the user by way of CFOUTPUT. You can also refer to them within a CFMAIL or in a CFQUERY to store data in a database record.

Showing all the variables in effect at the time of an error is a phenomenal capability. How often have you had an error arise and been challenged to determine the reason knowing only the template name? Perhaps the error was caused by form variables passed (or not passed) to the program or session variables, not set as expected.

You may be thinking that a major drawback to this concept is that youd need to know in advance what variables youd want to process and therefore couldnt capture all the variables in effect at the time of the processing of the error handler. More great news: you can!

Looping Through All Variables of a Given Type
You may know that Allaire has been making (in each release) more variables available as CF "structures." Early on, we could process application and session variables this way. As of 4.5, you can also access url, cgi, form, and cookie variables as structures (server variables are still not available, partially for security reasons).

One of the great things about being able to access these variable scopes as structures is that we can use the CFLOOP tag, using it's COLLECTION attribute, to identify the name and value of all variables in a given scope. The following shows an example of one way to loop through all session variables:

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

This first tests if session variables exist for the current user (if so, a session variable called CFID will exist), then loops through each existing session variable, printing it's name and value. If the value is not printable, this is explained. This could occur if the variable is itself a structure or perhaps a query. One way to better handle this problem is to use the custom tag CF_OBJECTDUMP, available free at the Allaire Developers Exchange. It can recursively display structures within structures.

The code example above may be a bit tricky on first viewing, but it works. Putting this sort of code block for each of the available variable scopes would be a great addition to any error handler. Again, whether you choose to display those, send them to support in an e-mail, or store them in a database record is up to you.

Note: While client variables cant be processed as structures, there's a function getclientvariableslist() that can be used to achieve a similar objective. It will return the empty string if there are no client variables.

"Admin E-mail" Address Also Available
In the previous article I mentioned the possibility of defining an e-mail address in the CF Administrator that would be displayed in the default CF error message shown. Users could then click on a link to e-mail that person about the error.

Of course, with the site-wide error handlers ability to send e-mail on it's own, it's not as important to show that sort of mail link to the user, but you may still prefer to use such a global setting to indicate who should receive the error notification.

The good news is that if this admin e-mail value is set in the Administrator, it will be available as an #error.mailto# variable in any site-wide error handler.

Errors in the Error Handler
Finally, those whove been using CF for a while may remember that early forms of error handling templates, namely the CFERROR TYPE="request" and TYPE="validation", didn't allow you to execute CF tags or functions. You could only display the error variables mentioned above with a sort of presumed CFOUTPUT that allowed their use.

The thinking, it was said, was that enabling CF tags and functions (and other variables) in the error handler could raise the dilemma that the error handler could have an error itself, and the system might get stuck in a loop of the error handler trying to process the error handler. It never quite made sense to me (and may have been an apocryphal explanation for the lack of access to tags and functions), as it seemed Allaire could detect an error in the error handler and simply abort the error handling process altogether.

The good news is that this is indeed the tack Allaire takes when using the site-wide error handler. If there's an error in the handler itself, then the user will simply be shown the plain old CF error message in the black on white that were all accustomed to.

Summary
There you have it. You should now have a better understanding as we'll as a working version of a site-wide error handling template. You've learned about the hierarchy of error handling mechanisms and how to catch errors that havent been otherwise caught by error handling mechanisms at the template or application levels.

You've learned how to access a host of error diagnostic variables, and perhaps more valuable (for all your coding), you've learned how to loop through the various CF variable scopes to be able to report on all the session variables - or nearly any other scope - in effect at the time of the error. And you've learned what happens when the error handler itself has an error.

For all it's capability, the site-wide error handling capability alone is not the only solution to implement to achieve "better error handling." Due to it's global nature, it may not always be the appropriate (or only) solution. Next month we'll continue the discussion with the next step down the hierarchy: application-level error handling via CFERROR.

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
"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...