Always var scope! Always!! Except...

So, I ran into an interesting issue today. We had some UDFs written in cfscript that used try/catch. The object defined in the cfcatch block was var scoped since… well… we always var scope, right? Consider this code block:

<FONT COLOR=MAROON><cfscript></FONT>
function foo() {
   var myerror = <FONT COLOR=BLUE>""</FONT>;
   x = <FONT COLOR=BLUE>"apple"</FONT>;
   try {
   if(x+9) x = 1;
   } catch(ANY myerror) {
      writeOutput(myerror.message & <FONT COLOR=BLUE>"<FONT COLOR=NAVY><p></FONT>"</FONT>);
   }
}
<FONT COLOR=MAROON></cfscript></FONT>

<FONT COLOR=MAROON><cfoutput></FONT>
#foo()#
<FONT COLOR=MAROON></cfoutput></FONT>

Everything looks hunkey-dorey, right? However, running this will give you: You have attempted to dereference a scalar variable of type class java.lang.String as a structure with members.

Turns out - the var scope of myerror seems to prevent it from being used in the cfcatch block. If you remove the var scope, not only does the code work right, it won’t overwrite a variable called myerrors that may exist in the Varibles scope.

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