[SalesForce] How to catch internal Salesforce error in APEX

I have a condition where i have to get a list of valid custom label names in a list using which i can display those custom labels dynamically on the page. But whenever i am checking if the custom label is valid using the following code:

String labelName = 'Label12345'
Component.Apex.OutputText output = new Component.Apex.OutputText();
output.expressions.value = '{!$Label.' + labelName + '}';
System.debug(String.valueOf(output.value));

The above code work perfectly fine when i send a valid custom label name but when i try executing the same with an invalid customlabel name the code is failing mentioning

FATAL_ERROR System.UnexpectedException: Internal Salesforce Error

I have tried embeddiing that in a try catch block with catch type as System.UnexpectedExcetion but even then its not entering the catch.

The code just fails each and everytime.

Any workarounds or methods to check whether a custom label is valid or not in order to send the list onto the page and dynamically call them so that the page doesn't fail due to invalid custom labels

Best Answer

Internal Server Errors are just that; errors that occur in the runtime environment that are not accounted for. For example, the runtime knows how to express a NullPointerException, but it doesn't know how to handle something like a missing translation. You can observe this in action with the following code (as of the time of this answer, anyways):

System.debug(
    Id.valueOf('00Y000000000000').getSObjectType()
    .getDescribe().getLabel()
);

Once the system encounters a situation it can't handle, the only thing it can safely do is to abort the current transaction, log the error, and inform the user. The reason why your Apex Code can't handle the exception is because it's occurring in the underlying runtime system.

If you've ever had a Blue Screen of Death on a Windows system, you could consider it to be roughly analogous to what's happening with an Internal Server Error. A BSoD halts the system so that no further damage can occur to the system. Similarly, an Internal Server Error halts the transaction so that the underlying system doesn't crash entirely.

If you want to determine the existence of a label, you're going to have to use an alternative API, such as the Metadata API wrapper. In the future, you should be able to use the Apex Metadata API, but this is not available in the current release (with no known date when CustomLabel will be supported).

Related Topic