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
RimaRima 

How to capture trigger error in controller extension

Hi All,

 

I am checking for the duplicate records using trigger. I have a VF page and controller extension to save the page.Could anyone please let me know how to capture trigger error in controller extension save method? When I enter duplicate record record is not saving, but  it is not displaying error message defined in the trigger. I am using  <apex:pageMessages to display error messages. Error message will be displayed only if I use standard "save" method , but not when I use controller extension "save" method. Could anyone please let me know what I need to change in the controller extension "save" method. I greatly appreciate your help.

 

 

public PageReference mysaveexit() {
      Sample__c individual = new Sample__c ();
    //  insert individual; 
    controller.save();
     PageReference pageRef = new PageReference('/a07/o');
     return pageRef;
     }

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

I've created a reduced version of your scenario and I'm seeing the same behaviour.  It looks like the standard controller save method doesn't throw an error if the save fails, it simply returns a null page reference that would keep the browser on the edit page.

 

I think that if you change your method to return null if the standard controller method returns null, you'll get the behaviour you desire.  Also, there's no need to add an error message, as adding an error in the trigger appears to populate a message that is displayed via the pagemessages component.

 

 

public PageReference mysaveexit() {
      Individual_Detail__c individual = new Individual_Detail__c ();
    //  insert individual; 
    if (null==controller.save())
    {
       return null;
    }
    PageReference pageRef = new PageReference('/a07/o');
    return pageRef;
}

 



 

 

All Answers

bob_buzzardbob_buzzard

What behaviour are you seeing when you use the controller extension?  Do you not see an error message, or are you redirected to a standard error page.

 

I'd expect you to have to wrap the controller.save() in a try/catch block and then add the error into the page in order to get the errors to appear in the apex:pageMessages component.

RimaRima

Hi,

 

Thank you for your response. I could able to display error message on VF page.I am using following code to accomplish this. Now I need to set boolean Errorcondition == true in my trigger. Do I need to declare ErrorCondition boolean in trigger as a global variable? Could you please give me your suggestion on this. Please let me know how to declare this as a global variable in trigger so that it can accessed in my controllerextension class.Your help is greatly appreciated.

 

 

if (ErrorCondition == true){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Add your message here');
ApexPages.addMessage(myMsg);
return null;
}

 

 

bob_buzzardbob_buzzard

Usually the way you'd do this it to execute the addError method on the sobject(s) that your trigger is processig.  This will cause the trigger to throw an exception on exit, which you can catch in your extension controller.

RimaRima

Hi,

 

Thank you for your response. I wrapped controller.save() method with try/catch block as follows:

 

 

try{
    controller.save();
   } catch (Exception e) {
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Add your message here');
   ApexPages.addMessage(myMsg);
   return null;
   }

 In the trigger I am using addError method

 

 

 Trigger.new[0].Unique_ID__c.addError('person with this name '
                                 + 'already exists.');

 

In VF I am using

<apex:pageMessages ></apex:pageMessages> 

 

It is still not displaying error message on the VF page. I think exception is not cought in try/catch block in my controllerextension class. Could you please let me know what is wrong with the code? Your help is greatly appreciated.

 

 

bob_buzzardbob_buzzard

What result are you seeing?  If the error wasn't being trapped by the visualforce page I'd expect your browser to be redirected to a platform error page.  Are you seeing that, or is your page simply refreshing?

RimaRima

Hi,

 

Thank you for your response.When I enter duplicate unique ID, it won't save the record.However, it will  refresh and show page where I can create another record. This behaviour is according to my code in mysaveexit() method in the controller extension.Functionality is working fine.Somehow it is not displaying the error message.The addError() in the trigger is not cought in the try/catch block of the controller extension.I greatly appreciate your help.

bob_buzzardbob_buzzard

Hmm.  That's very strange.  If the error wasn't being trapped, I wouldn't expect the page to be refreshed correctly.

 

Can you post the entire method - its a little tricky to figure out from snippets.

RimaRima

Hi,

 

Thank you for your response. Here is the trigger code

trigger IntakeDuplicatePreventer on Individual_Detail__c
                                (before insert, before update){
                                
   //    boolean ErrorCondition = false;
                             


   
      Map<String, Individual_Detail__c> intakeMap = new Map<String, Individual_Detail__c>();
      for (Individual_Detail__c intake : System.Trigger.new) {
           
          // Make sure we don't treat an email address that 
          // isn't changing during an update as a duplicate. 
       
          if ((intake.Unique_ID__c != null) &&
                  (System.Trigger.isInsert ||
                  (intake.Unique_ID__c !=
                      System.Trigger.oldMap.get(intake.Id).Unique_ID__c))) {
           
              // Make sure another new lead isn't also a duplicate 
       
              if (intakeMap.containsKey(intake.Unique_ID__c)) {
                  intake.Unique_ID__c.addError('Another new lead has the '
                                      + 'same email address.');
              } else {
                  intakeMap.put(intake.Unique_ID__c,  intake);
              }
         }
      }
       // Using a single database query, find all the leads in 
       
      // the database that have the same email address as any 
       
      // of the leads being inserted or updated. 
    //  public class myException extends Exception {}
       
      for (Individual_Detail__c intake : [SELECT Unique_ID__c FROM Individual_Detail__c
                        WHERE Unique_ID__c IN :intakeMap.KeySet()]) {
      //    Individual_Detail__c newIntake = intakeMap.get(intake.Unique_ID__c);
        ErrorCondition = true;
           ExtOne myException  = new ExtOne(ErrorCondition);
           
         
        Trigger.new[0].Unique_ID__c.addError('An intake with this name '
                                 + 'already exists.');
         
         //throw new MyException('The selected project already have a Scorecard attached.');
       
                                 
      }
  }

 

 

Here is my controller extension class

 

 

 

public with sharing class ExtOne {
    
    public Individual_Detail__c individual{ get; set; } 
    ApexPages.StandardController controller{get; set;}
    
            
            private String qp;                                   
  
    
    public ExtOne(ApexPages.StandardController stdController) {       
        this.qp = ApexPages.currentPage().getParameters().get('qp');     
        individual = (Individual_Detail__c)stdController.getRecord();
         controller = stdController;              
    }     
  
    
    
     public PageReference mysaveexit() {
      Individual_Detail__c individual = new Individual_Detail__c ();
    //  insert individual; 
    try{
    controller.save();
  }catch(Exception e){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Add your message here');
ApexPages.addMessage(myMsg);
return null;
}
     PageReference pageRef = new PageReference('/a07/o');
     return pageRef;
     }

 

Please let me know where I am going wrong.Thank you for your help.

 

 

 

bob_buzzardbob_buzzard

I've created a reduced version of your scenario and I'm seeing the same behaviour.  It looks like the standard controller save method doesn't throw an error if the save fails, it simply returns a null page reference that would keep the browser on the edit page.

 

I think that if you change your method to return null if the standard controller method returns null, you'll get the behaviour you desire.  Also, there's no need to add an error message, as adding an error in the trigger appears to populate a message that is displayed via the pagemessages component.

 

 

public PageReference mysaveexit() {
      Individual_Detail__c individual = new Individual_Detail__c ();
    //  insert individual; 
    if (null==controller.save())
    {
       return null;
    }
    PageReference pageRef = new PageReference('/a07/o');
    return pageRef;
}

 



 

 

This was selected as the best answer
RimaRima

Hi,

 

It is a perfect solution!! It is displaying the message on VF page when I try to save duplicate records. Thank you very much for taking your time to work on this. I greatly appreciate your help.