function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vijay NagarathinamVijay Nagarathinam 

Community exception

Hi All,

I am getting the below error in my community. I don't know how to handle this exception. 

The error message is: Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address).

Let me know how to handle this exception

Thanks,
Vijay
 
yogesh_sharmayogesh_sharma

Hi Vijay,

Could you please elaborate your use case, when you are getting this error.

Thanks,

Yogesh Sharma

Vijay NagarathinamVijay Nagarathinam
I am using self-registration page in the community.  If the user register the details in the page after submitting the details.  I am getting the above error

Thanks,
Vijay
Ravi Dutt SharmaRavi Dutt Sharma
Hi Vijay,

You cannot handle this error if you are using the standard self registration page of communitiy. This is a requirement from Salesforce that the username has to be unique across all the Salesforce org. If the end user is getting this error, then he has to register with some other username. If you want to handle this error, create a custom VF page for self-registration and have a try catch block. Then you can show a customized error message to the end user.
Vijay NagarathinamVijay Nagarathinam
Hi Ravi,

Thanks for your response. Currently, I am using custom vf page for self-registration page. But I am not able to handle this scenario. Becuase the username is unique for entire org. In this case, I am not able to get the details.

Can you help me how to resolve this issue?

Thanks,
Vijay
Ravi Dutt SharmaRavi Dutt Sharma
Hi Vijay,

Can you please post the controller code here. Thanks.
Nachiket Deshpande 33Nachiket Deshpande 33
Hi Vijay,

If you are creating User use following piece of Code for creating Unique Username
   
// Method dynamically creates a username prefix that will make ensure username uniqueness.
    public static String getUserNamePrefix(){
        return UserInfo.getOrganizationId() + System.now().millisecond();
    }//getUserNamePrefix
    
    //Method to return User
    public static User insertStandardUser(Id standardProfileId){
        User standardUser = new User(Username = getUserNamePrefix() + 'standarduser@testorg.com',
                                     Alias = 'standt',
                                     email = 'standarduser@testorg.com',
                                     emailencodingkey = 'UTF-8',
                                     LastName = 'Testing',
                                     LanguageLocaleKey = 'en_US',
                                     LocaleSidKey = 'en_US',
                                     ProfileId = standardProfileId,
                                     TimeZoneSidKey = 'America/Los_Angeles'

        );
        return standardUser;
    }//insertStandardUser
Let me know if this works for you!
Thanks,
Nachiket
Ravi Dutt SharmaRavi Dutt Sharma
Hi Nachlket,

This will ensure that username will be always unique, but this defeats the purpose of having a user friendly username. The prefix generated by getUserNamePrefix method will be very complicated and hard to remember.
Vijay NagarathinamVijay Nagarathinam
Hi,

Please refer the below controller.
 
public class AliantSelfRegController{    
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String Mobile {get;set;}
    Savepoint sp;
    public AliantSelfRegController() {}
    public void registerUser(){
        
        Set<String> emailSet = new Set<String>{email};
        List<Account> accList = new List<Account>();
        List<Lead> newLeadList = new List<Lead>();
        List<User> usersList = [SELECT Id, Username FROM User WHERE UserName = :email LIMIT 1];
        List<Account> accountList = [SELECT Id,personEmail,Email_2__c,Phone,personContactId FROM Account WHERE personEmail =: email  or Email_2__c =: email ];
        List<Lead> leadList = [SELECT Id,Email FROM Lead WHERE Email =: email AND isconverted = false];
        
        //If the email is already exist in User, then display an error message
        if(usersList.size() > 0 ){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'There is an account already exist with same details, please try and reset your password.');
            ApexPages.addMessage(msg);
            //return null; 
        }
        
        if(accountList.size() > 0){
            Set<Id> personContactIdSet = new Set<Id>();
            Set<String> personEmailSet = new Set<String>();
            for(Account acc : accountList){
                if(acc.personEmail != null && emailSet.contains(acc.personEmail)){
                    personContactIdSet.add(acc.personContactId);
                    personEmailSet.add(acc.personEmail);
                }
                else if(acc.Email_2__c != null && emailSet.contains(acc.Email_2__c) && !personEmailSet.contains(acc.Email_2__c)){
                    personContactIdSet.add(acc.personContactId);
                    personEmailSet.add(acc.Email_2__c);
                }
            }
            if(personContactIdSet.size() > 0 || personEmailSet.size() > 0){
                List<User> getUser = [SELECT Id,contactId,userName FROM User WHERE (contactId IN : personContactIdSet) OR (userName IN : personEmailSet)];
                //If the email is already exist in User, then display an error message
                if(!getUser.isEmpty()){
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'You have already registered with ' +getUser[0].userName +' .Please use this email to login.');
                    ApexPages.addMessage(msg);
                    //return null; 
                }
            }
        }
        
        Profile communityProfile = [SELECT Id,Name FROM Profile WHERE Name =: 'Community User'];
        Id personAccountRecTypeId = Schema.SobjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId(); 
        String accountId = ''; // To be filled in by customer.
        
        if(leadList.size() > 0 && accountList.size() == 0){
            Account newAccount = new Account(OwnerId = Label.OnlineDefaultUserID, FirstName = firstName,LastName = lastName, personemail = email, RecordTypeId = personAccountRecTypeId,phone = Mobile);
            accList.add(newAccount);  
        }
        else if(leadList.size() == 0 && accountList.size() == 0){
            Lead newLead = new Lead(FirstName = firstName, Lastname = lastName, Email = email, OwnerId = Label.OnlineDefaultUserID,Phone = Mobile,LeadSource = 'Online', Channel_Source__c = 'Application');
            newLeadList.add(newLead);
            Account newAccount = new Account(OwnerId = Label.OnlineDefaultUserID, FirstName = firstName,LastName = lastName, personemail = email, RecordTypeId = personAccountRecTypeId,Phone = Mobile);
            accList.add(newAccount);
        }
        String userName = email;
        User newUser = new User();
        newUser.Username = userName;
        newUser.Email = email;
        newUser.FirstName = firstName;
        newUser.LastName = lastName;        
        newUser.CommunityNickname = firstname.SubString(0,1)+lastname;
        newUser.ProfileId = communityProfile.Id;
        String userId;
        
            if(newLeadList.size() > 0)
                insert newLeadList; 
            if(accList.size() > 0)
                insert accList;
            if(accList.size() > 0 ){
                accountId = accList[0].Id;
            }
            else if(accountList.size() > 0){
                accountId = accountList[0].Id;  
            }
            userId = Site.createExternalUser(newUser, accountId); 
    }
}

Thanks,
Vijay
Nachiket Deshpande 33Nachiket Deshpande 33
Hi Vijay,

Put try and Catch block around 
if(newLeadList.size() > 0)
                insert newLeadList; 
            if(accList.size() > 0)
                insert accList;
            if(accList.size() > 0 ){
                accountId = accList[0].Id;
            }
            else if(accountList.size() > 0){
                accountId = accountList[0].Id;  
            }

       try{
            userId = Site.createExternalUser(newUser, accountId);
        } 
        catch(Exception e){
              //You can also add the page message here and show the exception message      //catched.
               system.debug('*****Exception*****'+e);
         }

Please elaborate more what exactly your requirment is! Do you want to handle this exception and show an userfriendly error message or do you want to generate unique username each time user register from site.

Please provide more details.

Thanks,
Nachiket
Vijay NagarathinamVijay Nagarathinam
Yes, I want to show user-friendly error message in the visualforce page.Can you help me how to resolve this issue? Need to fix .

Thanks,
Vijay
Nachiket Deshpande 33Nachiket Deshpande 33
Okay, then just catch the exception and show it on VF page using pageMessages.
 
try{
    userId = Site.createExternalUser(newUser, accountId);
} 
catch(Exception e){
    //You can also use e.getMessage() method to get the exact message and check if that contains string 
    //"Duplicate Username" then put your custom message
    //Or you can display as it is your choice
    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Your Exception Message or e.getMessage()');
    ApexPages.addMessage(msg);
}
Thanks,
Nachiket
Vijay NagarathinamVijay Nagarathinam
Hi Nachiket,

Thanks for the reply, still I am getting the duplicate username exception. Please let me know how to resolve this issue.

Thanks,
Vijay
Nachiket Deshpande 33Nachiket Deshpande 33
Vijay,
Could you please post your latest code and a screenshot of exception you are getting, that will help me undersatd issue to provide you better solution.

Thanks,
Nachiket
Vijay NagarathinamVijay Nagarathinam
public class SelfRegController{    
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String Mobile {get;set;}
    Savepoint sp;
    public AliantSelfRegController() {}
    public PageReference registerUser(){
        
        Set<String> emailSet = new Set<String>{email};
        List<Account> accList = new List<Account>();
        List<Lead> newLeadList = new List<Lead>();
        List<User> usersList = [SELECT Id, Username FROM User WHERE UserName = :email LIMIT 1];
        List<Account> accountList = [SELECT Id,personEmail,Email_2__c,Phone,personContactId FROM Account WHERE personEmail =: email  or Email_2__c =: email ];
        List<Lead> leadList = [SELECT Id,Email FROM Lead WHERE Email =: email AND isconverted = false];
        
        //If the email is already exist in User, then display an error message
        if(usersList.size() > 0 ){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'There is an account already exist with same details, please try and reset your password.');
            ApexPages.addMessage(msg);
            return null; 
        }
        
        if(accountList.size() > 0){
            Set<Id> personContactIdSet = new Set<Id>();
            Set<String> personEmailSet = new Set<String>();
            for(Account acc : accountList){
                if(acc.personEmail != null && emailSet.contains(acc.personEmail)){
                    personContactIdSet.add(acc.personContactId);
                    personEmailSet.add(acc.personEmail);
                }
                else if(acc.Email_2__c != null && emailSet.contains(acc.Email_2__c) && !personEmailSet.contains(acc.Email_2__c)){
                    personContactIdSet.add(acc.personContactId);
                    personEmailSet.add(acc.Email_2__c);
                }
            }
            if(personContactIdSet.size() > 0 || personEmailSet.size() > 0){
                List<User> getUser = [SELECT Id,contactId,userName FROM User WHERE (contactId IN : personContactIdSet) OR (userName IN : personEmailSet)];
                //If the email is already exist in User, then display an error message
                if(!getUser.isEmpty()){
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'You have already registered with ' +getUser[0].userName +'. Please use this email to login.');
                    ApexPages.addMessage(msg);
                    return null; 
                }
            }
        }
        
        Profile communityProfile = [SELECT Id,Name FROM Profile WHERE Name =: 'Community User'];
        Id personAccountRecTypeId = Schema.SobjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId(); 
        String accountId = ''; // To be filled in by customer.
        
        //If the registered details is  matched in the existing lead then create new account and user
        //for the applicant. 
        if(leadList.size() > 0 && accountList.size() == 0){
            Account newAccount = new Account(OwnerId = Label.OnlineDefaultUserID, FirstName = firstName,LastName = lastName, personemail = email, RecordTypeId = personAccountRecTypeId,phone = Mobile);
            accList.add(newAccount);  
        }
        //If there is no lead and prospect then create a lead convert into account.
        //Then create new community user for the applicant
        else if(leadList.size() == 0 && accountList.size() == 0){
            system.debug('>>>>empty lead and account condition');
            Lead newLead = new Lead(FirstName = firstName, Lastname = lastName, Email = email, OwnerId = Label.OnlineDefaultUserID,Phone = Mobile,LeadSource = 'Online', Channel_Source__c = 'Application');
            newLeadList.add(newLead);
            Account newAccount = new Account(OwnerId = Label.OnlineDefaultUserID, FirstName = firstName,LastName = lastName, personemail = email, RecordTypeId = personAccountRecTypeId,Phone = Mobile);
            accList.add(newAccount);
        }
        String userName = email;
        User newUser = new User();
        newUser.Username = userName;
        newUser.Email = email;
        newUser.FirstName = firstName;
        newUser.LastName = lastName;        
        newUser.CommunityNickname = firstName + lastname + Mobile.right(3);
        newUser.ProfileId = communityProfile.Id;
        String userId;
        
        try{
            sp = Database.setSavepoint();
            if(newLeadList.size() > 0)
                insert newLeadList; 
            if(accList.size() > 0)
                insert accList;
            if(accList.size() > 0 ){
                accountId = accList[0].Id;
            }
            else if(accountList.size() > 0){
                accountId = accountList[0].Id;  
            }
            userId = Site.createExternalUser(newUser, accountId);
        }
        catch(DMLException ex) {
            Database.rollback(sp);
            system.debug('>>> DML Exception >>>>');
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ex.getMessage()));
            // This message is used for debugging. Do not display this in the UI to the end user.
            // It has the information around why the user creation failed.
            System.debug(ex.getMessage());
            System.debug(ex.getLineNumber());
            
        }
        
        if(userId != null) { 
            PageReference page = System.Page.CommunitiesSelfRegConfirm;
            page.setRedirect(true);
            return page;
        }
        return null;
    }
}

 
Nachiket Deshpande 33Nachiket Deshpande 33
Although I am not sure but can you try catching the generic exception instead of DMLException for following piece of code
try{
            sp = Database.setSavepoint();
            if(newLeadList.size() > 0)
                insert newLeadList; 
            if(accList.size() > 0)
                insert accList;
            if(accList.size() > 0 ){
                accountId = accList[0].Id;
            }
            else if(accountList.size() > 0){
                accountId = accountList[0].Id;  
            }
            userId = Site.createExternalUser(newUser, accountId);
        }
        //User Generic Exception instead of DMLException
        catch(Exception ex) {
            Database.rollback(sp);
            system.debug('>>> DML Exception >>>>');
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ex.getMessage()));
            // This message is used for debugging. Do not display this in the UI to the end user.
            // It has the information around why the user creation failed.
            System.debug(ex.getMessage());
            System.debug(ex.getLineNumber());
            
        }

Thanks,
Nachiket
Nachiket Deshpande 33Nachiket Deshpande 33
The  problem here is you are getting exception in site method however you are catching DML excpetion, so try catching generic exceptions and let me know if that works for you.

Thanks,
Nachiket
Vijay NagarathinamVijay Nagarathinam
Still I am getting the same exception.. :)
Nachiket Deshpande 33Nachiket Deshpande 33
please share the screenshot
Nachiket Deshpande 33Nachiket Deshpande 33
As per my understanding exception is fine because UserName must be unique, however you need to catch the exception and display it as a page message correct ?
Vijay NagarathinamVijay Nagarathinam
You are correct Nachiket
Nachiket Deshpande 33Nachiket Deshpande 33
Then it should work, whatever exception you are getting will be displayed on VF page , what exactly you mean that you are getting exception I didn't understand your usecase. Ain't Page message is getting displayed on VF Page? Did you add apex: pagemessage tag on VF page? What do you mean by you are getting same exception?
Vijay NagarathinamVijay Nagarathinam
Yes, I added the apex page message tag in my visualforce page. If the user registers the details on the registration page, I am not getting any exception message on my page. I am getting the same exception in the debug log.