[SalesForce] System.NoAccessException: Script-thrown exception while UserManagement.verifyPasswordlessLogin

community.

We are implementing Passwordless Login in Lightning community.
While we receive verification code on email, and verify it with following piece of code

@AuraEnabled
public static String SendCode(String code, String username, String identifier, String method){ 

        PageReference target;
        Auth.VerificationResult res;
        try {
        if(username != null){
            List<User> users = getUserByUsername(username); //simple method with SOQL that retrieves User by Username
            if(users != null && users.size() > 0){
                if(method == 'email'){
                     res = UserManagement.verifyPasswordlessLogin(users[0].Id, Auth.VerificationMethod.EMAIL, identifier, code, null); // the code fails on this line
                }else if(method == 'phone'){
                    res = UserManagement.verifyPasswordlessLogin(users[0].Id, Auth.VerificationMethod.SMS, identifier, code, null);
               }
                if(res.success){
                    target = Page.CommunitiesLanding;
                    target.setRedirect(true);
                    aura.redirect(target);
                }else{
                    return 'error';
                }
            }
        }
        }catch(Exception ex){
            System.debug('ex: ' + ex);
        }
        return '';
     }

The code fails with following exception:

09:02:35.0 (16885931)|VARIABLE_ASSIGNMENT|[194]|ex|"common.apex.runtime.impl.ExecutionException: Script-thrown exception"|0x258d8415
[...]
09:02:35.0 (16998696)|HEAP_ALLOCATE|[195]|Bytes:53
USER_DEBUG|[195]|DEBUG| ex: System.NoAccessException: Script-thrown exception

I wonder what can be an issue? I assume it is something with session settings or community administration.
Any help is much appreciated.

Best Answer

Script thrown exception hides the actual exception message, this happens for custom exception classes extending from Exception.

I suggest trying to use ex.getMessage() for your logs - it could provide more information than what we have so far.