0

I have written a scheduler for deactivating salesforce users who doesn't logged in for last 90 days. The code is working as expected if I remove exception logging into a salesforce object at line #14. When I put this facing Mixed DML operation (Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you...)

Please help me to resolve this exception.

public class DeactivateInactiveUsers implements Schedulable {
    public void execute(SchedulableContext context) {
        try{
            List<string> toAddress = new List<string>();
            User[] selectedUsers = [SELECT Id FROM User WHERE IsActive = TRUE AND Id NOT IN (SELECT UserId FROM LoginHistory WHERE LoginTime = LAST_N_DAYS:90)];
            for(User record: selectedUsers) {
                record.IsActive = false;
                toAddress.add(record.email);
            }
            Database.update(selectedUsers, false);
        }
        catch(System.Exception e) {
            String strException = 'Exception Type: ' + e.getTypeName() + '-Message: ' + e.getMessage() + '-Cause: ' + e.getCause() + '-Line Number: ' + e.getLineNumber() + '-Stack Trace: ' + e.getStackTraceString();
            ErrorloggingClass.logErrors(strException, 'DeactivateUser');
        }
    }
}   
0

1 Answer 1

2

By allowing partial updates (Database.update(records, false)), you're allowing a partial update; if an exception is later thrown, you've already modified some user records, and so you'd get this exception. Your best option would be to change your ErrorloggingClass to use Platform events to deliver the exception data asynchronously to a Platform Event Trigger and log the data.

You must log in to answer this question.

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