I have this trigger where it adds new user to chatter group but it throws exceptions everytime when i reset the password or when i deactivate any user, how can i update the trigger to not throw any exceptions?
Trigger:
trigger CompanyChatter on User (after insert, after update) {
UserMethods.addToMainGroup(trigger.newMap.keySet());
}
Apex class:
public class UserMethods {
@future
public static void addToMainGroup(Set<Id> userIds) {
List<User> users=[select id, Username from User where id in :userIds];
CollaborationGroup chatterGroup=[select Id from CollaborationGroup Where Name='My Company, Inc'];
List<CollaborationGroupMember> chatterGroupMembers=new List<CollaborationGroupMember>();
for(User user: users){
CollaborationGroupMember newMember = new CollaborationGroupMember(CollaborationGroupId=chatterGroup.id, MemberId = user.Id, NotificationFrequency = 'P');
chatterGroupMembers.add(newMember);
}
if(!Test.isRunningTest()){
insert chatterGroupMembers;
}
}
}
Exceptions
For Reset passwords:
Developer script exception from SonoSite, Inc : 'UserMethods' for job id '7073300002yuF1b' : Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, User is already a Member of this group.: [MemberId]
When i deactivate users:
First error: Insert failed. First exception on row 0; first error: INACTIVE_OWNER_OR_USER, operation performed with inactive user [00540000002ome5]