function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
anjisalesforce@gmail.comanjisalesforce@gmail.com 

How to handle the exception in Trigger?

Hi all,

 

Q) How to handle the exception in Trigger?

 

Please give answer with Example..

 

Thanks for u r help......

anyioneta1.3025054394678596E12anyioneta1.3025054394678596E12

Does this help in any way :

This is a trigger that throws an exception whenever you want to enter a duplicate product

 

rigger productDuplicatePreventer on Product__c (before insert, before update) {

    Map<String, Product__c> prodMap = new Map<String, Product__c>();
 
    for(Product__c prod: System.Trigger.new) {

// Make sure we don't treat an Product that isn't changing during an update as a duplicate.
if ((prod.Name != null) &&
(System.Trigger.isInsert || (prod.Name != System.Trigger.oldMap.get(prod.Id).Name))) {
 
// Make sure another new product isn't also a duplicate
if (prodMap.containsKey(prod.Name)) {
 prod.Name.addError('Another new Product has this same Product Name');
} else {
prodMap.put(prod.Name, prod);
}
  }
}

// Using a single database query, find all the products in the database that have the same
//product Name as any of the product being inserted or updated.
for (Product__c prod : [SELECT Name FROM Product__c WHERE Name IN :prodMap.KeySet()]) {
Product__c newProd = prodMap.get(prod.Name);
newProd.Name.addError('A Product with this Product Name already exists.');
}
}