2

I get an exception error when a button is clicked and tries to insert an event record. This is expected in that users are doing something I don't want them to. However, two messages appear one that is the system validation rule and then the error on the insert. Is there a way to only show one message?

From this? enter image description here

To this? enter image description here

I've been playing with severity but I don't seem to be getting the syntax right.

 try{
        insert event;   
    }
    Catch(DMLException ex){
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()));

    }
    return null;
    try{    
9
  • you can replace ex.getMessage() with your own custom message and it will be displayed as single error message
    – Himanshu
    Jul 18, 2016 at 18:08
  • 1
    Are you doing try/catch? Can you show us more context?
    – Adrian Larson
    Jul 18, 2016 at 18:11
  • @AdrianLarson I edited to show my try/catch Jul 18, 2016 at 18:25
  • @DanWooding any luck with getDmlMessage() method of the DMLException ?. As mentioned in my answer.
    – Praveen
    Jul 18, 2016 at 18:26
  • 1
    The pattern that often works best and involves least code is to use the ApexPages.addMessages(exceptionThrown) method and directly pass it the DmlException.
    – Keith C
    Jul 18, 2016 at 19:09

1 Answer 1

5

you can use try/catch block and get the appropriate exception messages using DMLException's getDmlMessage.More methods can be found here.

try{
    insert new Event(Subject = 'Name');
}
catch(DmlException de) {
    Integer numErrors = de.getNumDml();
    for(Integer i=0;i<numErrors;i++) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, de.getDmlMessage(i))); 
    }
}

@KeithC Suggested a clean and robust way, to show exception in using ApexPages.addMessages().Click here to know more.

try{
    insert new Event(Subject = 'Name');
}
catch(DmlException ex) {
   ApexPages.addMessages(ex); 
}
3
  • @DanWooding Glad I could help :-)
    – Praveen
    Jul 18, 2016 at 18:31
  • 1
    You should catch DMLException, not generic Exception. We used to call that a "pokemon catch" as in "gotta catch em all!" If you know a specific type you are expecting, catch only that type.
    – Adrian Larson
    Jul 18, 2016 at 19:36
  • Lol, Ya I totally agree.I have updated the answer.Thanks for pointing out @AdrianLarson
    – Praveen
    Jul 18, 2016 at 19:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .