You need to sign in to do that
Don't have an account?
Chris Shade
Trouble Catching Error
We have a custom field called Unique Email that is enforced to be unique. This field is populated by a apex trigger that runs before inserting/updating. I'm trying to use try/catch to take an alternate action if this error is experienced but the catch doesn't seem to be happening:
Here is my code:
trigger uniqueEmail on Contact (before insert, before update) {
for (Contact c : Trigger.new) {
try{
c.Unique_Email__c = c.Email;
}
catch(Exception a){
system.debug(c.id);
c.Unique_Email__c = NULL;
List<Contact> contactList = new list<Contact>();
contactList = [SELECT Id,Email,Remove__c
FROM Contact
WHERE email = :c.Email AND id != :c.id
LIMIT 100];
for(Contact updateContact : contactList)
{
updateContact.Remove__c = FALSE;
update updateContact;
}
if(c.id==Null){
c.Unique_Email__c = NULL;
Delete c;
}
else{
for(Contact cOld : trigger.old){
c.Unique_Email__c = NULL;
}
}
//insert email code
}
}
}
Here is my code:
trigger uniqueEmail on Contact (before insert, before update) {
for (Contact c : Trigger.new) {
try{
c.Unique_Email__c = c.Email;
}
catch(Exception a){
system.debug(c.id);
c.Unique_Email__c = NULL;
List<Contact> contactList = new list<Contact>();
contactList = [SELECT Id,Email,Remove__c
FROM Contact
WHERE email = :c.Email AND id != :c.id
LIMIT 100];
for(Contact updateContact : contactList)
{
updateContact.Remove__c = FALSE;
update updateContact;
}
if(c.id==Null){
c.Unique_Email__c = NULL;
Delete c;
}
else{
for(Contact cOld : trigger.old){
c.Unique_Email__c = NULL;
}
}
//insert email code
}
}
}
if you have a custom controller and you are doing save (insert /update) via your code use try catch there
All Answers
The document doesn't say it specifically, but I'm making a good guess that you aren't able to catch the error because the error is happening before your trigger code fires.
if you have a custom controller and you are doing save (insert /update) via your code use try catch there