Throw errors in a cfscript and try catch in cfscript

You CAN’T throw an error or errors from a cfscript without defining your own throw function. But this is pretty easy to do. Somewhere else in your code, just write a <cfunction name=”throw” etc. and in this function just put a <cfthrow tag that throws the error you want to be thrown. A good practice would be to include a throw function in a utility cfc that you could invoke wherever you needed to throw an error in a cfscript.

See the example code below. Note the interesting syntax for catching in a cfscript where you do catch(ERRORTYPE CFCATCHVARIABLE). So catch(database e), catch(any e) would be some common ones. And then you could access e.Message, e.Detail, etc.

try
{
//nothing below the throw would execute in this example.
//But I left the rest for syntax reference.
somethingWrong=true;
if(somethingWrong){
throw("ExampleErrorType","Example Error message.");
}
//save the reactor record without interfering with custom transaction
template1.save(useTransaction=false);
}
catch (database err)
{
//if the save fails and the error is a database error, return the error detail.
//otherwise this error will need to be caught by the code calling this code.
return err.Detail;
}

If you want to do a rethrow, the following article has a great example.
http://www.coldfusionjedi.com/index.cfm?mode=entry&entry=3089633C-9FA0-606B-3F540AE9642A795F

Leave a Reply

Your email address will not be published. Required fields are marked *