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:

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

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:

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

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