Copy link to clipboard
Copied
Sometimes i am getting "Element col1 is undefined in a CFML structure referenced as part of an expresssion".
How to trap this errror so that it does not throw any exception
Copy link to clipboard
Copied
1. Use StructKeyExists to check for the key before using it
or
2. Use cftry in combination with cfcatch around the code that
generates the error.
In 99% of the cases I've used StructKeyExists to check if the key
exists (catching an error is more expensive and doesn't allow you to
control the flow of the code in the same way as StructKeyExists).
Mack
Copy link to clipboard
Copied
Thank you Mack.
If i had known the name of the object i can use StructKeyExists , what about dynamically created objects.
Copy link to clipboard
Copied
StructKeyExists works for dynamic objects also. The second parameter
is the name of the key so it can be a hardcoded string, a variable, a
string returned from a function, etc.
Mack
Copy link to clipboard
Copied
In most cases, you do know what struct-keys to expect. When you don't, you can usually get what you want by <cfloop>ing over the structure itself. You can also, of course, obtain a list of the keys.
To handle the case of bumping into a struct-key that doesn't exist, well, you've got two good choices ... depending on how probable you consider the event to be, and/or if the presence or absence of a key "means something."
It all pretty-much coms down to your personal preference, because ColdFusion is typically not used to handle computationally-intensive nor time-consuming work. Whatever makes your code cleanest and most-reliable is the path that you should take.