Help CF Help You...

So, unlike the rest of you guys, I never make any mistakes. No, really, I don’t. But, I know people who do make mistakes. In fact, my good buddy (the same guy who is watching and reviewing all those cool shows in England) recently told me that he makes one mistake quite often - and that is trying to use an invalid key of a struct. So, consider the following code:

<cfset s = structNew()>
<cfoutput>#s.foo#</cfoutput>

When run, ColdFusion will tell you:
Element FOO is undefined in S.

Which is helpful and all, but wouldn’t it be cool if ColdFusion would tell you what WAS defined in the structure? Well, as Nimer pointed out a few days ago, the ColdFusion exception handler is a ColdFusion template itself. It can be found in /web-inf/exception/detail.cfm. It can also be modified. Look for line 110 (in CFMX7), and it should be:

#attributes.message#

Then simply add this code immidiately after:

<!--- is struct? --->
<cfif findNoCase("is undefined in", attributes.message)>
   <cfset theVar = listLast(attributes.message," ")>
   <!--- get rid of period --->
   <cfset theVar = left(theVar, len(theVar)-1)>
   <cfif structKeyExists(caller, theVar) and isStruct(caller[theVar])>
      <cfif not structIsEmpty(caller[theVar])>
      Valid keys are: #structKeyList(caller[theVar])#
   <cfelse>
      #theVar# is an empty struct.
   </cfif>
</cfif>
</cfif>

All this does is check the message (I should check the exception type instead most likely), find the variable name, see if it exists, and then checks if it is a struct. It then either shows you the keys or tells you that it is empty. Enjoy.

FYI - the tabbing got a bit messed up above. Ignore my poor choice of pasting.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments