Reputation: 6110
I have cfcatch block that should catch any exception. Once error detected I build custom function that takes NativeErrorCode
as an argument. If error code is one that I'm looking for that indicates duplicate/PK violation I have custom message that will return to the user. If error code is not one that I'm looking for then global message will be returned. However, I run in the problem where ColdFusion returned error message that NativeErrorCode
does not exist. I know that Native Error Code is reserved for database type. Is there a way to check the type and prevent this problem or there is better way to fix this issue? Here is my code example:
<cftry>
// Stored procedure call
<cfcatch type="any">
<cfset local.fnResults = {status : "400", message : Application.functions.errorCatch(cfcatch.NativeErrorCode)}>
</cfcatch>
</cftry>
public string function errorCatch(required string ErrorCode) {
local.message = "";
if(arguments.ErrorCode EQ 2627){
local.message = "Error! Cannot insert duplicate value.";
}else{
local.message = "Error! Please contact your administrator.";
}
return message;
}
You can see above how my errorCatch
function works and what code I'm checking. I still want cfcatch
to grab any exception in my code not just database errors.
Upvotes: 0
Views: 374
Reputation: 1466
Two ways come to mind for handling your branching catch logic, have 2 catch blocks, or check the catch object has the data you want.
In my first example I added a catch block exclusively for database errors. If the type of the error is database a Native Error Code will be included or be -1 if the database driver doesn't include one. For the any argument, I just added your default return string. You may want to have custom logic that would handle non-database type exceptions.
<cftry>
// Stored procedure call
<cfcatch type="database">
<cfset local.fnResults = {status : "400", message : Application.functions.errorCatch(cfcatch.NativeErrorCode)}>
</cfcatch>
<cfcatch type="any">
//Non database related error
<cfset local.fnResults = "Error! Please contact your administrator.">
</cfcatch>
</cftry>
In my second Example I just updated your errorCatch function with a check that a NativeErrorCode exist before we try to pass it.
<cfcatch type="any">
//Passing the default error code value, you may want custom logic here
<cfset local.fnResults = {
status : "400",
message : Application.functions.errorCatch( cfcatch.keyExists("NativeErrorCode")?cfcatch.NativeErrorCode:-1)
}>
</cfcatch>
Upvotes: 2