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.

//nothing below the throw would execute in this example.
//But I left the rest for syntax reference.
throw("ExampleErrorType","Example Error message.");
//save the reactor record without interfering with custom transaction;
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.

Leave a Reply

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