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
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
In this presentation, Striim CTO and founder Steve Wilkes will discuss practical strategies for counteracting fraud and cyberattacks by leveraging real-time streaming analytics. In his session at @ThingsExpo, Steve Wilkes, Founder and Chief Technology Officer at Striim, will provide a detailed look into leveraging streaming data management to correlate events in real time, and identify potential breaches across IoT and non-IoT systems throughout the enterprise. Strategies for processing massive ...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...