I have seen the other threads discussing this issue where the validation rule error messages from a Trigger are added to the VF pages <apex:pageMessages />
. However, in my case, we have a custom object that will be inserted and in the case of a DML exception through the validation rule, an update is performed instead. In my case, I do not want the VF page to show the exception message at all. I have tried
try
{
// insert operation
}catch(DmlException dex)
{
ApexPages.addMessages(dex);
// perform my update operation
// if OK, remove the apex message.
ApexPages.getMessages().clear();
}
I have also tried to remove Apex Messages in my controller class before I add a success message if everything else is OK. But no matter, what I do, the exception message from the DML exception is shown on the screen.
If you think, this is badly designed. I would like to hear some ideas on how to overcome it as well. The trigger is written for duplicate check and the field that indicates the duplicate is actually another SObject. So, I am unable to do this through a simple duplicate check on the variable. Would be happy for any help or guidance.
Thanks!
-- New edit
I only added the ApexPages.addMessages(dex) above because it was suggested as a way to handle this issue.
But even without that, I can see the custom message popping up in my container.
This is the original code I had:
try {
insert myObj;
}catch(QueryException e) {
System.debug('QueryException in insertOrUpdate : '+e.getMessage());
throw new CustomException('Unable to XXX',e);
}
catch(DmlException dex)
{
System.debug('DmlException in insertOrUpdate: '+dex.getMessage());
if(dex.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'))
{
try {
update myObj;
return 'SUCCESS';
}catch(QueryException e) {
System.debug('QueryException in insertOrUpdate : '+e.getMessage());
throw new CustomException('Unable to XXX',e);
}
}
throw new CustomException('Unable to XXX',e);
}
return 'SUCCESS';