1

In an application I am reading configuration values from a custom setting. This custom setting has a data set with a few fields, like username, password, enabled, and a few more.

ApiCredential__c is the name of the custom setting and the data set is called AppDettings.

I have a class called AppSettingsController which is used for displaying and updating the configuration values.

I have the following code:

ApiCredential__c objAppDetails;
try
{
    System.debug('Checking if app details are set');
    objAppDetails = ApiCredential__c.getValues('AppDetails');
}
catch(Exception ex)
{
    System.debug('App details are not set');
}

For new apps, when the custom setting is not set, when this code runs an error occurs on the objAppDetails = ... line. The code does not go into the catch(Exception) statement.

How can I handle when a custom setting is not set?

2 Answers 2

2

From the documentation about List type custom settings

getValues(dataSetName)

If no data is defined for the specified data set, this method returns null.

It will not throw an exception, it simply returns a null value.

System.debug('Checking if app details are set');
ApiCredential__c objAppDetails = ApiCredential__c.getValues('AppDetails');
if (objAppDetails == null) {
    System.debug('App details are not set');
}

For completeness, the original code with the same check:

ApiCredential__c objAppDetails;
try
{
    System.debug('Checking if app details are set');
    objAppDetails = ApiCredential__c.getValues('AppDetails');

    if (objAppDetails == null) {
        System.debug('App details are not set');
    }
}
catch(Exception ex)
{
    System.debug('Something went terribly wrong.');
}
6
  • But isn't this how I am doing it already?
    – andrewb
    Commented Mar 21, 2018 at 23:13
  • No. Does my code look exactly like yours? A method returning null is not the same as throwing and catching an exception.
    – Mark Pond
    Commented Mar 21, 2018 at 23:15
  • Right, but my line of objAppDetails = ApiCredential__c.getValues('AppDetails'); is the same as yours, except the code does not go into my catch statement, as stated
    – andrewb
    Commented Mar 21, 2018 at 23:16
  • ApiCredential__c.getValues() does not throw an exception when there is no data. It returns null. Updated the answer with your original code in addition to my rewrite.
    – Mark Pond
    Commented Mar 21, 2018 at 23:20
  • I made progress - my code wrapped in a try/catch is inside a separate try/catch, but when an exception occurred it jumped to the outer catch statement, which was not logging anything to debug
    – andrewb
    Commented Mar 22, 2018 at 11:36
0

I would suggest using getALL first, it would return the map of all the data sets, You can check whether the setting exists or not.

You must log in to answer this question.

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