Wednesday, December 11, 2013

System.Exception: SObject row does not allow errors

Scenario:
 Error: System.Exception: SObject row does not allow errors
  
   This Exception is thrown when your adding an error message to particular record in a list which is looping through For Loop and that list gets records from the Trigger.oldMap context variable in Trigger.You can you use the addError method for only those records that are available in Trigger Context. 

Trigger Example:

 trigger BeforeDeleteConatct on Contact (Before Delete)
{
 Set<Id> conSet=Trigger.OldMap.keyset();
 List<Contact> listCon=[select id,phone from contact where id in:conset];

 for(Contact c:listCon)
 {
  if(c.Phone!=null)
  {
    System.debug('.......c......'+c);
    c.addError('you cant delete this contact because  it conatins Phone Number');
   }
  }
}

When you click on delete button of a particular contact it throws below error

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger BeforeDeleteConatct caused an unexpected exception, contact your administrator: BeforeDeleteConatct: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.BeforeDeleteConatct: line 11, column 1". 
Work Around to Resolve This Error:

 trigger BeforeDeleteConatct on Contact (Before Delete)
{
 Set<Id> conSet=Trigger.OldMap.keyset();
 List<Contact> listCon=[select id,phone from contact where id in:conset];

 for(Contact c:listCon)
 {
  if(c.Phone!=null)
  {
    System.debug('.......c......'+c);
    Add below line of code to resolve Error
    Contact actualRecord = Trigger.oldMap.get(c.Id);
    actualRecord.addError('you cant delete this contact bcz it conatins Phone Number');
   }
  }
}

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "you can't delete this contact because it conatins Phone Number".

1 comment: