Find your content:

Search form

You are here

How to trap a System Error Message

 
Share

Is there a way to trap system error messages? An example would be for a unique field violation. There are times that I would like to provide a richer set of error info than is provided by the built in system error.

Edit: Unfortunately, this is a system exception that happens in the background. Set a field as unique, when a duplicate value is entered and the form is saved, the error is thrown without going through any of my code. This means that I cannot trap the error in a standard Try/Catch block since I am not explicitly running any SOQL or DML.

For example: I have a multi-part key for a given object. I want to be able to give a more detailed error message letting the user know exactly why they are getting the duplicate value error.


Attribution to: Dwight

Possible Suggestion/Solution #1

There is a workaround:

I did for better messages sent for my site user:

}catch(DmlException d){
               String dup = d.getMessage();
               if(dup.containsIgnoreCase('DUPLICATE_VALUE')){
                   ApexPages.Message errorDup = new ApexPages.Message(ApexPages.severity.INFO,'Your custom mesg here');
                   ApexPages.addMessage(errorDup);
               }else{
                   ApexPages.Message errorDml = new ApexPages.Message(ApexPages.severity.INFO,'another custom mesg:' + d);
                   ApexPages.addMessage(errorDml);
                   ApexPages.Message alertMessageDml = new ApexPages.Message(ApexPages.severity.INFO,'yet another custom mesg ');
                   ApexPages.addMessage(alertMessageDml);                       
               }

Attribution to: Bruno Lube

Possible Suggestion/Solution #2

if you use a try {} catch(exception e) {} you can add code to check for specific execptions in the catch and display them as Page Messages.

The DML that throws the exception goes in the try part.


Attribution to: Patrick Dixon

Possible Suggestion/Solution #3

Catch the System.Exception and throw it as your custom exception with your custom message

  try {
     --- your code --
  }catch(System.Exception e){
   if(e.getTypeName() == 'System.NullPointerException')
    e.setMessage('-- your message --');

    throw new CustomException(e.getMessage());

}


Attribution to: logontokartik

Possible Suggestion/Solution #4

I know this question is a few years old now but I had this problem myself recently and wanted to share what I feel is possibly the only solution, since I can't find one anywhere else.

Since duplicate unique Id validation is standard behaviour and the error message gets posted on your visualforce page without any involvement from you, there's no way to stop it, but what you can do is hide it with jQuery. If you inspect the HTML of the error message you'll see it's contained within a couple of spans and a div with the style classes 'message' and 'errorM3'. The standard message will also always contain the text "Duplicate external id specified". We can use this to find and hide the message:

$j(document).ready(function () {
 $j( "div.errorM3:contains(': Duplicate external id specified')" ).hide();
});

This will, when the DOM is ready, search for a div with the class 'errorM3' and containing the text ': Duplicate external id specified'. If it finds it it'll hide it, but leave your custom ApexPages.Message untouched.

This is all correct at the time of writing but should Salesforce change their class names or the wording of their error message (Which they can do without notice) then you'll need to update the search criteria. Hope this helps!


Attribution to: ministe2003

Possible Suggestion/Solution #5

If the only system error you're running into is the "unique field" issue, how about you query for that value before you try to save? If you find a duplicate already in the database, prevent the save from happening.

Integer oldConCount = [select count() from Contact 
    where Unique_Field__c = :newContact.Unique_Field__c];
if (oldConCount > 0)
    ApexPages.addMessage(ApexPages.Severity.ERROR, 'That's not unique enough.');
else
    insert newContact;

Attribution to: Jeremy Nottingham

Possible Suggestion/Solution #6

Based on your comment:

In certain instances, I have a multi-part key for a given object. I want to be able to give a more detailed error message letting the user know exactly why they are getting the duplicate value error.

You could add a trigger before insert and update that could include your tests and use the addError() method to set the detailed error message.

It might even be possible to have a trigger after insert and update that looked for the generic error message on each entry in Trigger.new, and then replaced it with something more detailed.

Here's an example of a trigger on a custom object, where we set the Name field to a combination of two other fields. It checks the length of the new value and sets one error if it's too long, and sets another error if it's not unique. The trigger builds a map of Name to Id for the duplicate check.

trigger update_name on External_Account__c (before insert, before update) {
    // create a map of existing Ids for each account name
    Map<String, Id> dbnames = new Map<String, Id>{};
    for (External_Account__c acct : [SELECT Id, Name
                                  FROM External_Account__c])
    {
        dbnames.put( acct.Name, acct.Id);
    }

    for (External_Account__c acct : Trigger.new)
    {
        if (acct.username__c.length() + acct.server__c.length() > 79)
        {
            acct.addError( 'Combined length of Username and Server fields ' +
                           'must be less than 80 characters.');
        }
        else
        {
            acct.Name = acct.username__c + '@' + acct.server__c;
            if (Trigger.isUpdate && acct.Device_Count__c > 0)
            {
                External_Account__c oldrec = Trigger.oldMap.get( acct.Id);
                if (oldrec.Name != acct.Name)
                {
                    acct.addError( 'Username and Server fields cannot be modified.');
                }
            }

            Id existing_id = dbnames.get( acct.Name);
            if (existing_id != Null && existing_id != acct.Id)
            {
                acct.addError( 'Duplicate account ' + acct.Name);
            }
        }
    }

}

Attribution to: tomlogic
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1199

My Block Status

My Block Content