How can I prevent ColdFusion from saying a defined variable is undefined?

136 Views Asked by At

In our CF code, inside a larger page/application, we have a block something like this (minus the dumps to the page - they are logged to a DB table):

<cftry>
    <cfparam name="session.awesomeInfo" default="">
    
    <cfset somethingNew = session.awesomeInfo>
    
    <cfcatch type="any">
        <cfdump var="#cfcatch#">
        <cfdump var="#session#">
    </cfcatch>
</cftry>

99.9% of the time, this works great. But once every few days, a user will hit this code and the cfcatch will be thrown. The cfcatch will point to the line with the cfset, and it'll say Element AWESOMEINFO is undefined in SESSION. However, there in the session that's dumped is awesomeInfo, right where it's supposed to be, with a non-null value. And, in the context of the page, it's after lots of other logic that looks at many other session-scoped variables without issue.

Any ideas what would cause this, or more importantly, how to prevent it from happening? It feels like maybe a server-level or CF-application-level problem. We're currently running Adobe ColdFusion 2018 Standard.

1

There are 1 best solutions below

1
lhoess On

Not sure it matters, but move the cfparam outside the try block.

If you're always passing a string, setting the type might prevent unwanted data types. You'll need to set in anywhere session.awesomeInfo is set using cfparam.

Here are two options you could use.

<!--- Moved outside try block --->
<cfparam name="session.awesomeInfo"  type="string" default="">

<cftry>
    <!--- Option A --->
    <cfif structKeyExists(session,"awesomeInfo")>
        <cfset somethingNew = session.awesomeInfo& " awesomeInfo Struct Key Exists.<br>">
    </cfif>
    <cfoutput>#somethingNew#</cfoutput>

    <!--- Option B --->
    <cfif isDefined("session.awesomeInfo")>
        <cfset somethingNew = session.awesomeInfo& " Session awesomeInfo isDefined.<br>">
    </cfif>
    <cfoutput>#somethingNew#</cfoutput>
    

    <cfcatch type="any">
            <cfdump var="#cfcatch#">
            <cfdump var="#session#">
    </cfcatch>
</cftry>