Amcom Home Page

 cfcatch Gotcha (it got me)

The other day I had a client call about a bug in an application that we had released a few weeks back. This particular piece of the application allows users to import an Excel spreadsheet, which is parsed and inserted into a database. The reported bug was that the user (apparently) successfully imported their .xls file (no errors were reported by the system), but the records didn't show up in subsequent searches. Hmm....

The majority of the import happens within a single method. At the top of the method, I declare a variable to hold any potential error messages... initially set to an empty string:

<cfset var insertErrorMsg = "" />

Further down in the method, the actual SQL INSERT is done within a <cftry> block. actually, it's a number of INSERTs done inside of a <cfloop>. after each INSERT, i have the following <cfcatch>:

<cfcatch type="database">
	<cfset insertErrorMsg = cfcatch.detail />
	<cfbreak />
</cfcatch>

At the end of the method, if the length of the value of the insertErrorMsg variable is 0, I assume all is well and indicate to the user that their import was successful.

In this case, however, all was not well. Something went horribly, horribly wrong and under a specific set of circumstances (which I later identified), a specific variable that was intended to be an integer was sent into the method as an empty string. ColdFusion would error with Invalid data '' for CFSQLTYPE CF_SQL_INTEGER. Why then, wasn't my bulletproof error handling working? I added a <cfmail> to the <cfcatch> with a dump of the <cfcatch> scope:

Note the empty string for the detail key. Yeah, I know. So there were any number of easy fixes that could have been done (using the cfcatch.message string, or incrementing an errorCount variable that's initially set to zero). It's not so much about the solution as it is about the problem. This isn't one that I would have anticipated. Thought it was worthwhile to throw out there in case others may be using, or considering using, similar conditional logic.

Comments
Jason Fisher's Gravatar Sadly, I have found that many errors return blank Details, but not all, which definitely makes this type of error-length tests difficult. What has always bothered me has been that the Message property of cfcatch is always populated, but it's not always where the useful information is. In instances where Details is *not* blank, it seems that the Message is so generic that's it's useless without the Details. For quick & dirty tests where I don't want to parse the cfcatch struct on every report, I've even resorted to this approach:

cfset insertErrorMsg = cfcatch.message & " :: " & cfcatch.detail

That way I will get Len() on my error while still getting as much information as possible without having to parse and deal with StackTrace etc.

-jfish
# Posted By Jason Fisher | 10/10/08 9:11 AM

BlogCFC was created by Raymond Camden. This blog is running version 5.9.002. Contact Blog Owner