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

Tracking Errors: How Good Is Your Code?

Tracking Errors: How Good Is Your Code?

Nobody likes errors, but the bottom line is, they're a fact of programming life. The better you are at pinpointing them, the better your code will get. Unfortunately, ColdFusion has never provided very good functionality for tracking the errors that occur within your production applications. I mean how many of you actually look through your application.log? For those of us with busy servers and busy schedules, that becomes an impossibility...

Thus good tools are needed. ColdFusion 4 and 5 and MX include a Log Files reporting tool in the CF Administrator. For some, that still may not be enough. It would be helpful, for instance, to extract the log of errors into a database for subsequent reporting. Right off the bat, it seems Allaire/Macromedia didn't fully think things through as the application.log is not easily parsed.

The problem is, when certain types of errors occur (such as ODBC errors), quotes appear within the text of the error and that interferes with the quotes used as field delimiters for the log. Rather than give up on our goal, however, we can find an alternative solution. What if we could handle errors ourselves rather than rely solely on after-the-fact log analysis?

Enter ColdFusion's error handling. Since version 4.5, Macromedia has made available improved error handling. One of the early restrictions CF developers faced was not being able to run any ColdFusion code on an error-handling page. It was the old chicken and egg problem - what happens if an error occurs on the error-handling page? Fortunately we don't have to worry about those kinds of restrictions anymore.

There are several ways of dealing with errors by executing ColdFusion tags, such as CFTRY/CFCATCH, the CFERROR tag (using TYPE=Exception), and the site-wide error handler that can be enabled through the CF Administrator. These have been discussed in various previous CFDJ articles, such as Charlie Arehart's four-part series starting in October 2000 at www.sys-con.com/coldfusion/article.cfm?id=165.

In this article, we'll take advantage of the site-wide error handler, which will catch any errors that fall through the cracks and interrupt a page from running.

There are a couple of things to be aware of about error handling, such as with the site-wide handler. First, when using it to intercept an error, CF will not write the error to the application.log. You'll have to do that yourself if you really want to (see Listing 1).

Listing 1: Writing out to application.log
<cflog text="#error.diagnostics#" log="APPLICATION"
type="Error" thread="yes" date="yes"
time="yes" application="yes">

Since our end result was to parse the application.log and insert that into a database, we'll skip the step of writing out the log and insert each error directly into the database as it occurs.

Listing 2 contains the database tables that we'll use for our application. Note the "fixID" field at the end of the "errorLog" table. We'll set that as we correct our errors so that we know which ones have been fixed.

Listing 2: Table and index creation
CREATE TABLE errorLog (
logID int IDENTITY (1,1) NOT NULL,
application varchar(20) NULL,
errorDetail varchar(2200) NULL,
errorBase64 varchar(3000) NULL,
errorStamp datetime NOT NULL,
errorType varchar(30) NULL,
browser varchar(100) NULL,
remoteAddr varchar(15) NULL,
httpReferer varchar(255) NULL,
server varchar(30) NULL,
template varchar(255) NULL,
scriptName varchar(200) NULL,
queryString varchar(120) NULL,
fixID smallint NULL
)

PRIMARY KEY: logID
INDEXES: fixID, errorDetail, errorBase64, errorType, application, template

CREATE TABLE errorFixes (
fixID int IDENTITY (1,1) NOT NULL,
logID int NULL,
fixDetail varchar(500) NULL,
fixStamp datetime NULL
)

PRIMARY KEY: fixID
INDEXES: logID

Listing 3 contains the CF code for your site-wide error handler that will insert the error into the database. There are several error types that are common to ColdFusion and might be present in your application (see Table 1). We'll later produce a report that groups things by these types, so we'll add some code right before the insert query to determine the type of error that has occurred. Feel free to add additional code to catch specific errors that you want grouped into the "Other" category.

Listing 3: Inserting the error via SQL
<Cflock scope="application" type="readonly" timeout="10">
<Cfset variables.appName = #application.applicationName#>
</cflock>

<cfif Left(trim(error.diagnostics),4) is 'ODBC' or
Left(trim(error.diagnostics),5) is 'OLEDB' or
Left(trim(error.diagnostics),30)
is 'Error Executing Database Query'>
<cfset errorType = "Database Error">
<cfelseif Left(trim(error.diagnostics),17) is 'Request timed out'>
<cfset errorType = "Request Timeout">
<cfelseif error.diagnostics contains 'Error resolving parameter'>
<cfset errorType = "Error Resolving Parameter">
<cfelseif error.diagnostics contains 'Error resolving parameter <B>SESSION.'>
<cfset errorType = "Session Timeout">
<cfelseif Left(trim(error.diagnostics),53) is
'<P>An error occurred while evaluating the expression:'>
<cfset errorType = "Error Evaluating Expression">
<cfelseif Left(trim(error.diagnostics),30) is 'Just in time compilation error'>
<cfset errorType = "Compilation Error">
<cfelse>
<cfset errorType = "Other Error">
</cfif>

<cfquery name="InsertLogRecord" datasource="#request.datasource#">
INSERT INTO errorLog (errorStamp, errorDetail, errorBase64, errorType, template,
queryString, browser, remoteAddr, httpReferer, application, server, scriptName) VALUES
(#CreateODBCDateTime(error.DateTime)#, '#left(trim(error.diagnostics),2200)#',
'#Trim(Left(ToBase64(error.diagnostics),3000))#', '#errorType#', '#error.template#',
'#error.queryString#','#error.browser#', '#error.RemoteAddress#',
'#ERROR.HTTPReferer#', '#variables.appName#', '#cgi.server_name#', '#cgi.script_name#')
</cfquery>

Note that you could add more to this logging of information, such as writing out session identifiers (CFID, CFTOKEN, and/or JSessionID if using J2EE sessions in CFMX). Also, the locking of access to the application.applicationname variable is something that could be removed if this code is run in CFMX.

Of course, this listing is just a fragment of what you could do in the error handler. For more information on site-wide error handlers, including how to create one, how to provide notification to the user about the error, and optionally how to send e-mail notification to someone in your shop about the error, see the second part in the previously mentioned series, "Toward Better Error Handling - Part 2: Site Wide Error Handling" from December 2000, at www.sys-con.com/coldfusion/article.cfm?id=181.

You may notice that I chose to create a column called errorBase64. Let me explain, and you may need to make some adjustments based upon your database. Specifically, if your database cannot handle sub-selects (as we'll explain later and see in Listing 5), we cannot do comparisons directly within the database given the approach we'll be using. Therefore we'll need a way to encode special characters such as quotes. Most enterprise databases such as Oracle and MS SQL will have no problems with sub-selects, and MS Access supports them as well, but some databases such as mySQL do not (although support is coming soon).

Fortunately, there is an easy workaround. You can add one additional field to your database table to store the error encoded in Base64 (we've reflected this in the code listings). Those of you who store binary files directly in your databases may already be familiar with the ToBase64() function which does just that. If your database does handle sub-selects, you can ignore all references to Base64 as you won't need to do any conversions.

Now that we're collecting all of our errors, we need a way to make sense of it all.

So what's next? Well, we need a way to sort and organize our errors so that we can start to see which are our biggest problems. In our completed application, we've created a CFC called error.cfc with a number of CFFUNCTION methods that are used to search the database we've created. There are several ways you may want to sort including by template, by application, newest first, most frequent, and by type of error. Later we'll look at some different ways to sort and view your errors. For now, we'll just list the newest errors first (see Listing 4). Notice that we added the "WHERE fixID IS NULL" line to our query in order to not include errors that have already been corrected.

Listing 4: Newest errors
<cffunction name="byNewest" displayName="Newest Errors"
access="public" returnType="query" output="false">
<cfset var getErrors = "">
<cfquery name="getErrors" datasource="#request.datasource#">
SELECT logID, application, errorDetail, errorStamp FROM errorLog
WHERE fixID IS NULL
ORDER BY errorStamp DESC
</cfquery>
<cfreturn getErrors>
</cffunction>

We might then call that CFC using code such as:

<cfinvoke component="errors" method="byNewest"
returnvariable="GetErrors"></cfinvoke>
<cfoutput query="getErrors">#application# : #errorDetail# :
#errorStamp#<br></cfoutput>

The code in Listing 5 will display an individual error. You should set up a separate page to drill down to this info. The GetSimilar query will show you how many times the specific error you're viewing appears in the log. You'll need to comment out either the "with sub-selects" or "without sub-selects" portion of the code depending upon your database's capabilities. We then add one column to the end of our original query listing the "SimCount," or the number of times a matching error appears.

Listing 5: Get detail
<cffunction name="getDetail" displayName="Get Error Detail"
access="public" returnType="query" output="false">
<cfargument name="logID" type="numeric" required="true">
<cfset var getError = "">
<cfset var getSimilar = "">
<cfset var simCount = arrayNew(1)>
<cfquery name="getError" datasource="#request.datasource#">
SELECT * FROM errorLog WHERE logID = #ARGUMENTS.logID#
</cfquery>
<!--- with sub-selects --->
<cfquery name="GetSimilar" datasource="#request.datasource#">
SELECT count(*) as numSimilar FROM errorLog
WHERE errorDetail = (SELECT errorDetail FROM errorLog
WHERE logID = #ARGUMENTS.logID#)
AND logID != #ARGUMENTS.logID#
</cfquery>

<!--- without sub-selects --->
<cfquery name="GetSimilar" datasource="#request.datasource#">
SELECT count(*) as numSimilar FROM errorLog
WHERE errorBase64 = '#getError.errorBase64#'
AND logID != #ARGUMENTS.logID#
</cfquery>

<!--- create an array and add column to query --->
<cfset simCount[1] = GetSimilar.numSimilar>
<cfset QueryAddColumn(getError, "SimCount", simCount)>
<cfreturn getError>
</cffunction>

To keep our error log manageable, we need a way to mark errors as corrected once the code has been fixed. At the bottom of the screen displaying an individual error, we'll add a textarea field for entering the fix we performed. When we submit a fix, we'll mark the error as solved (see Listing 6) and also update all of the matching errors since those should now be corrected also (note the slight query changes depending on whether your database can handle sub-selects).

Listing 6: Enter problem fix
<cffunction name="enterFix" displayName="Enter Problem Fix"
access="public" returnType="void" output="false">
<cfargument name="logID" type="numeric" required="true">
<cfargument name="errorFix" type="string" required="true">
<cfset var enterFix = "">
<cfset var getMatching = "">
<cfset var getBase64 = "">
<cfset var getMatching = "">
<cfset var updateLogTable = "">
<cfquery name="enterFix" datasource="#request.datasource#">
INSERT INTO errorFixes (logID, fixDetail, fixStamp)
VALUES (#ARGUMENTS.logID#, '#ARGUMENTS.errorFix#',
#CreateODBCDateTime(Now())#)
</cfquery>

<!--- with sub-selects --->
<cfquery name="GetMatching" datasource="#request.datasource#">
SELECT logID FROM errorLog WHERE errorDetail =
(SELECT errorDetail FROM errorLog WHERE logID = #ARGUMENTS.logID#)
</cfquery>

<!--- without sub-selects --->
<cfquery name="GetBase64" datasource="#request.datasource#">
SELECT errorBase64 FROM errorLog WHERE logID = #ARGUMENTS.logID#
</cfquery>
<cfquery name="GetMatching" datasource="#request.datasource#">
SELECT logID FROM errorLog WHERE errorBase64 =
'#GetBase64.errorBase64#'
</cfquery>

<cfquery name="updateLogTable" datasource="#request.datasource#">
UPDATE errorLog SET fixID = #enterFix.id# WHERE logID IN
(#ValueList(getMatching.logID)#)
</cfquery>
</cffunction>

We now have a way to list, view, and fix the latest errors that occur. Next we'll look at various other ways of sorting and viewing our data. Previously we only listed the newest errors first - now we'll sort by application, template, top errors, and error types (see Listings 7-10). These views will allow you to see which errors are occurring the most based upon your selection criteria. The errCount alias in each query will keep track of the number of errors for that grouping and the maxStamp alias will hold the last date that an error for that grouping has occurred.

Listing 7: Errors by application
<cffunction name="byApplication" displayName="Errors By Application"
access="public" returnType="query" output="false">
<cfset var getErrors = "">
<cfquery name="getErrors" datasource="#request.datasource#">
SELECT application, count(logID) as errCount,
max(errorStamp) as maxStamp FROM errorLog
WHERE fixID IS NULL
GROUP BY application
ORDER BY errCount DESC
</cfquery>
<cfreturn getErrors>
</cffunction>

This could be called with:

<cfinvoke component="errors" method="byApplication"
returnvariable="GetErrors"></cfinvoke>
<cfoutput query="getErrors">#application# : #errCount# :
#maxStamp#<br></cfoutput>

Listing 8: Errors by template
<cffunction name="byTemplate" displayName="Errors By Template"
access="public" returnType="query" output="false">
<cfset var getErrors = "">
<cfquery name="getErrors" datasource="#request.datasource#">
SELECT template, application, count(*) as errCount,
max(errorStamp) as maxStamp FROM errorLog
WHERE fixID IS NULL
GROUP BY template, application
ORDER BY errCount DESC
</cfquery>
<cfreturn getErrors>
</cffunction>

This could be called with:

<cfinvoke component="errors" method="byTemplate"
returnvariable="GetErrors"></cfinvoke>
<cfoutput query="getErrors">#template# : #application# : #errCount# :
#maxStamp#<br></cfoutput>

Listing 9: Top errors
<cffunction name="byTopErrors" displayName="Top Errors" access="public"
returnType="query" output="false">
<cfset var getErrors = "">
<cfquery name="getErrors" datasource="#request.datasource#">
SELECT errorDetail, application, count(logID) as errCount,
max(errorStamp) as maxStamp, max(logID)as maxLogID
FROM errorLog
WHERE fixID IS NULL
GROUP BY errorDetail, application
ORDER BY errCount DESC
</cfquery>
<cfreturn getErrors>
</cffunction>

This could be called with:

<cfinvoke component="errors" method="byTopErrors"
returnvariable="GetErrors"></cfinvoke>
<cfoutput query="getErrors"> #application# : #errorDetail# : #errCount# :
#maxStamp#<br></cfoutput>

Listing 10: Errors by error type
<cffunction name="byErrorType" displayName="Errors By Error Type"
access="public" returnType="query" output="false">
<cfset var getErrors = "">
<cfquery name="getErrors" datasource="#request.datasource#">
SELECT errorType, count(*) as errCount, max(errorStamp) as maxStamp
FROM errorLog
WHERE fixID IS NULL
GROUP BY errorType
ORDER BY errCount DESC
</cfquery>
<cfreturn getErrors>
</cffunction>

This could be called with:

<cfinvoke component="errors" method="byErrorType"
returnvariable="GetErrors"></cfinvoke>
<cfoutput query="getErrors"> #errorType# : #errCount# :
#maxStamp#<br></cfoutput>

Used effectively, this tool will speed your application performance and improve your coding style. Good luck!

More Stories By Joe Danziger

Joe Danziger is a senior web applications developer with Multimax, Inc., a provider of Enterprise IT Services and Solutions supporting the critical missions of the Air Force, Army, Navy, and other Department of Defense components. He is certified as an Advanced Macromedia ColdFusion MX Developer, and also maintains the Building Blocks site (www.ajaxcf.com) dedicated to AJAX and ColdFusion, as well as DJ Central (www.djcentral.com), a Website serving DJs and the electronic dance music industry.

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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"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.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
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 ...
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.
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.
"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.
"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...
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...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
"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...
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...
"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.
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.