Salesforce Try Catch does not work with FeatureManagement checkPermission

apexfeature-managementtry-catchunexpectedexception

When working with FeatureManagement.checkPermission() a try-catch block does not catch system exceptions.

How to replicate:

Run the code below in execute anonymous. You will find that you receive a System.UnexpectedException: Salesforce System Error, instead of what is expected which is the catch block executing.

The reason for this error is that checkPermission() is expecting an API name for your permission. This API name should not have any spaces, unlike my example below. A proper execution flow with a useful exception would have helped me to narrow down this issue sooner.

try{
    Boolean hasCustomPermission = FeatureManagement.checkPermission('some permission');
    system.debug('User has permission: ' + hasCustomPermission);
}catch(Exception e){
    system.debug('User did not have permission to perform the operation');
}

Best Answer

Sorry to say, but System.UnexpectedException can generally not be caught. That's by definition, e.g. see here

What you could do is criticize that the exception thrown under these circumstances is of this type. Or maybe this is what you wanted to do in the first place?!

Related Topic