I am catching a duplicate insert error in a carrierDAO object as follows:
// CREATE
public string function newCarrier(required Carrier) {
// I insert a new carrier record in the database taking as argument a Carrier bean populated with the data to insert.
var insertKey = “”;
try {
var q = new Query();
q.setDatasource("#dsn.name#");
q.setSQL(“INSERT INTO tab_carriers (car_carrier_cd, car_carrier_nm, car_transport_mode, car_awb_prefix)
VALUES (:carrierCD, :carrierName, :carrierMode, :carrierAWBprefix)”);
q.addParam(name: “carrierCD”, value: “#Ucase(Trim(arguments.Carrier.getCarrierCD()))#” , cfsqltype: “CF_SQL_VARCHAR” );
q.addParam(name: “carrierName”, value: “#Ucase(Trim(arguments.Carrier.getCarrierName()))#” , cfsqltype: “CF_SQL_VARCHAR” );
q.addParam(name: “carrierMode”, value: “#Ucase(Trim(arguments.Carrier.getCarrierMode()))#” , cfsqltype: “CF_SQL_CHAR” );
q.addParam(name: “carrierAWBprefix”, value: “#Ucase(Trim(arguments.Carrier.getCarrierAWBprefix()))#” , cfsqltype: “CF_SQL_VARCHAR” );
qInsert = q.execute();
// Should any error arise in the process
} catch (any e) {
// Display an error message to the user on the [carriers.newCarrier] view
writeOutput("Error: " & e.message );
// Stop all processing at this point until the user hits the CANCEL button on the [carriers.newCarrier] view
abort;
}
// Here, we return either the numeric generatedKey value, which is an auto-generated value from mySQL
// or we simply return the string record key value already available from the bean
insertKey = arguments.Carrier.getCarrierCD();
return insertKey;
}
When I simulate the error, I do get an error message displayed for the event: [carriers.create] as defined in the corresponding handler:
function newCarrier(event,rc,prc){
// I display a form to input the details of a new carrier with the option to CREATE that record or CANCEL the process
event.setView(“carriers/newCarrier”);
}
function create(event,rc,prc){
// I process the creation of a carrier record in conjunction with the newCarrier event
var carrier = populateModel( “carrier”);
carrierSVC.create(carrier);
// validate it
var vResults = validateModel( carrier );
// Check it
if( vResults.hasErrors() ){
flash.put( “errors”, vResults.getAllErrors() );
return newCarrier(event,rc,prc);
}
else{
flash.put( “notice”, “Carrier Created!” );
setNextEvent(“carriers”);
}
}
My question is: how to get this error message displayed within the [carriers/newCarrier] view instead of on a blank page splashed by the [carriers.create] event? I guess the error message should be relayed from the DAO to the handler which in turn should pass it to the view, but how to do that?
Assumptions: focus is on best practices for Coldbox exception handling, everything else works fine otherwise.