So I am having some trouble displaying an error that happens on the Opportunity sObject.
Currently, there is a validation rule that works perfectly. However, this is usually only hit when I save an Opportunity Product.
The problem I am having is displaying a cleaner error message.
Currently, the best I can do is display the stack trace when an error occurs. I don't want that. I makes users flip out when they see it.
I tried putting my DML in a try/catch block and if it failed, but it gives me the following error:
... System.FinalException: SObject row does not allow errors: ...
Not the output I had in mind.
The following code below is executed during an after update event on the OpportunityLineItem sObject. I am hoping there is a way to update the error code to a simple message like 'Opps, my bad.' (obviously something more meaningful, but you get the idea).
public with sharing class M_OpportunityService
{
public void AssignOpportunityCorrectBrands(Set<Id> opportunityIds)
{
Map<Id, Set<String>> opportunityToBrandMap = new Map<Id, Set<String>>();
for(OpportunityLineItem singleLineItem : [SELECT OpportunityId, Brand__c FROM OpportunityLineItem WHERE OpportunityId IN :opportunityIds])
{
if(!opportunityToBrandMap.containsKey(singleLineItem.OpportunityId))
opportunityToBrandMap.put(singleLineItem.OpportunityId, new Set<String>());
opportunityToBrandMap.get(singleLineItem.OpportunityId).add(singleLineItem.Brand__c);
}
List<Opportunity> opportunitiesToBrand = [SELECT Id FROM Opportunity WHERE Id IN :opportunityIds];
for(Opportunity singleOpportunity : opportunitiesToBrand)
singleOpportunity.mkto71_Brand__c = String.join(new List<String>(opportunityToBrandMap.get(singleOpportunity.Id)), ';');
try{ UPDATE opportunitiesToBrand; }
catch(Exception error)
{
if(!Trigger.isExecuting)
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please choose the correct stage prior to saving.'));
else
for(Opportunity singleOpportunity : opportunitiesToBrand)
singleOpportunity.addError('Please choose the correct stage prior to saving.');
}
}
}