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
dsh210@lehigh.edudsh210@lehigh.edu 

Overriding Error Messages

Hey,

 

I was looking to enhance user experience by providing some better error messages. The one I am trying to overload now, is where it does not have an ID it needs in the URL, so rather than saying 'List out of bounds', I would like to explain to users that they need to go back and select a new ID to continue. I tried the following:

LIST<Model_Definition__c> temp = [SELECT Name FROM Model_Definition__c WHERE Id = :ModelDefId LIMIT 1];
    try {
        return temp[0].Name;
    }
    catch(Exception e){
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error: No objects could be found. Most likely, you no longer have a model selected. Please return to the model selection screen'));
    }
    return null;

 

 

but I still get a blank page displaying just the list out of bounds error. Does anyone know the proper way to override those error pages/messages?

 

Thanks!

rscottrscott

In this particular case, why not check the list size before trying to access it?

 

ex. if (temp.size()==0) {

// add your error message

}

dsh210@lehigh.edudsh210@lehigh.edu

While I do think that is a great solution in this case, I was really wondering if there was a general way to throw custom errors back to the user, since it is not always going to be a list out of bounds. Another error I have is a 'No rows found for assignment in SObject'.

rscottrscott

Ok. You should be able to trap this error. This worked for me.

 

In the controller:

 

		try {
			string n = 'NoUserInMySystem';
			List<User> uList = [select Id, name from User where name=:n];
			string s = uList[0].name;
		} catch (Exception ex) {
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error: ' + ex.getMessage()));
		}

 and one of these on the page: <apex:pageMessages />

 

 

I prefer testing for errors I know may happen rather than wait until they become exceptions. For your other error 'No rows found for assignment in SObject', you can set the result of your query to a list and then check the size.

 

ex. List<sObject> sList = [select Id from object where field=x];

if (sList.size()==0) {

// 'No rows found for assignment in SObject'

}