0

I have a Custom Action on Contact object that calls a lightning component. This Lightning component calls on init an Apex Controller function to, based on the contact recordId, find the Contact details and then create a user based on those details. My problem is the following: I also want to handle an Exception, where if the Exception message is about existing username, i want to return to the component the user and then showing an input field with the value of User.Username. However, when i am on exception and throw an AuraHandledException, i cannot get the user's username. So, how could i get the user.Username from the returned message of the Exception ? Code Below:

APEX CONTROLLER

//2020-05-08 @galaios Apex Class Controller for EnablePartnerUser Lightning Component

public without sharing class PartnerUserController {
    //Function that will create Automatically a user from Contact Record
    @AuraEnabled
    public static User createUserFromContact(String contactId) {
        User newCommunitiesUser;
        try {
            Contact objectContact = [SELECT FirstName,LastName,Email,AccountId 
                                 FROM Contact Where Id =: contactId LIMIT 1];

            COGNT__System_General_Settings__c system_sets = COGNT__System_General_Settings__c.getOrgDefaults(); //Get the organization default system settings to get the default profile

            //Select community profile that you want to assign
            Profile pf = [SELECT Id FROM profile 
                          WHERE name=: system_sets.COGNT__Partner_User_Default_Profile__c LIMIT 1];
            //Create user 
            newCommunitiesUser = new User(contactId=objectContact.Id, 
                                               username=objectContact.Email, 
                                               firstname=objectContact.FirstName,
                                               lastname=objectContact.LastName, 
                                               email=objectContact.Email,
                                               communityNickname = objectContact.LastName + '_'+Math.random(),
                                               alias = string.valueof(objectContact.FirstName.substring(0,1) + 
                                                                      objectContact.LastName.substring(0,1) + Math.random() ).substring(0,5), 
                                               profileid = pf.Id, emailencodingkey='UTF-8',
                                               languagelocalekey='en_US', 
                                               localesidkey='en_US', 
                                               timezonesidkey='America/Los_Angeles');                  
            insert newCommunitiesUser;
            return newCommunitiesUser;
        } catch(DMLException ex) {
            if(ex.getDMLMessage(0).contains('Duplicate Username')) {
              //throw new AuraHandledException('[ERROR] Cannot enable communities access, a user with this email address already exists.');
              throw new AuraHandledException('Duplicate username: ' +newCommunitiesUser);
            } else {
                throw new AuraHandledException(ex.getMessage());
            }
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    @AuraEnabled
    public static boolean isAccountPartner(id contactId) {
        try {
            //Get the contact based on input id
            Contact objectContact = [SELECT FirstName,LastName,Email,AccountId 
                                     FROM Contact Where Id =: contactId LIMIT 1];
            //Get the Account record of the contact
            Account contactAccount = [SELECT Id, Name, isPartner from Account where id=: objectContact.AccountId];
            return contactAccount.IsPartner;
        } catch (Exception e) {
            throw new AuraHandledException('Exception occured: ' +e.getMessage());
        }
    }
}

CMP

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickActionWithoutHeader" access="global"
                controller="PartnerUserController">
    <!-- Handlers Declaration -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <!-- Define Attributes -->
    <aura:attribute name="spinner" type="boolean" default="false"/>
    <aura:attribute name="isDuplicateUsername" type="boolean" default="false"/> <!-- Defines whether isername is Duplicate so let user insert another username -->
    <aura:attribute name="communityUser" type="User" /> <!-- The created user record -->

    <!--Loading spinner section -->
    <div class="slds-is-relative">
        <aura:if isTrue="{!v.spinner}">
            <div aura:id="spinnerId" class="slds-spinner_container">
                <div class="slds-spinner--brand  slds-spinner slds-spinner--large slds-is-relative" role="alert">
                    <span class="slds-assistive-text">Loading</span>
                    <div class="slds-spinner__dot-a"></div>
                    <div class="slds-spinner__dot-b"></div>
                </div>
            </div>
        </aura:if>
        <!--Loading spinner end-->
    </div>

    <aura:if  isTrue="{!v.isDuplicateUsername}" >
        <!--05/09/2019 George Galaios: Email1-->
            <!--Username--><lightning:input aura:id="username" type="email" placeholder="abc@domain.com" name="username" label="Username" value="{!v.communityUser.Username}" />
    </aura:if>
</aura:component>

CONTROLLER JS

({
    doInit : function(component, event, helper) {
        component.set("v.spinner", true);
        var recordId = component.get("v.recordId");
        var action = component.get("c.isAccountPartner"); //Call Apex to get the event
        action.setParams({"contactId" : recordId});
        action.setCallback(this, function(response) {
            var State = response.getState();
            if(State==="SUCCESS"){
                var isPartner = response.getReturnValue();
                console.log('is partner ' +isPartner);
                if (isPartner) {
                    var insertUser = component.get("c.createUserFromContact"); //Call Apex to get the event
                    insertUser.setParams({"contactId" : recordId});
                    insertUser.setCallback(this, function(response) {
                        var insertUserState = response.getState();
                        if(insertUserState==="SUCCESS"){
                            var returnedUser = response.getReturnValue();
                            console.log(returnedUser);
                            component.set("v.communityUser", returnedUser);
                            console.log(component.get("v.communityUser.Username"));
                            component.set("v.spinner", false);
                        } else if(insertUserState == "INCOMPLETE"){ //Case of Incomplete request
                            component.set("v.spinner", false);
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                                "title": $A.get("$Label.c.Oops"),
                                "message": $A.get("$Label.c.No_interned_connection"),
                                type: "warning",
                                mode: "sticky"
                            });
                            toastEvent.fire();
                        } else if(insertUserState == "ERROR"){ //Case of error calling Apex method
                            component.set("v.spinner", false);
                            if (response.getError()[0].message.includes("Duplicate username")) {
                                console.log('Error message is: ' +response.getError()[0].message);
                                var errorWords = response.getError()[0].message.split(' '); //Slpit the words of the error message
                                console.log('error words length is: ' +errorWords.length);
                                console.log('User is: ' +errorWords[3]);
                                component.set("v.communityUser", errorWords[3].Username); //
                                console.log('after set to user!');
                                component.set("v.isDuplicateUsername", true); //set the isDuplicateUsername attribute to true in order to show the email field
                            }
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                                "title": $A.get("$Label.c.Error"),
                                "message": response.getError()[0].message,
                                type: "error",
                                mode: "sticky"
                            });
                            toastEvent.fire();                    
                        }
                    });
                    $A.enqueueAction(insertUser);
                } else { //Account is not Partner
                    component.set("v.spinner", false);
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        "title": $A.get("$Label.c.Error"),  
                        "message": $A.get("$Label.c.Account_of_Contact_Not_Partner"),
                        type: "error",
                        mode: "sticky"
                    });
                    toastEvent.fire(); 
                }
            } else if(State == "INCOMPLETE"){ //Case of Incomplete request
                component.set("v.spinner", false);
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": $A.get("$Label.c.Oops"),
                    "message": $A.get("$Label.c.No_interned_connection"),
                    type: "warning",
                    mode: "sticky"
                });
                toastEvent.fire();
            } else if(State == "ERROR"){ //Case of error calling Apex method
                component.set("v.spinner", false);
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": $A.get("$Label.c.Error"),  
                    "message": $A.get("$Label.c.Account_of_Contact_Not_Partner"),
                    type: "error",
                    mode: "sticky"
                });
                toastEvent.fire();                    
            }
        });
        $A.enqueueAction(action);
    }        
})
2
  • I see you're trying to pass the entire user object through your error message: throw new AuraHandledException('Duplicate username: ' +newCommunitiesUser); What are you seeing on the client side, how is newCommunitiesUser received?
    – EranV
    May 8 '20 at 13:57
  • Hi EranV and thanks for the response. Yes, this is what i am trying to do. So the whole error message is seen on the client side as follows: Duplicate username: User:{ContactId=0035I000003bqeiQAA, Username=test1@gmail.com, FirstName=Andreas, LastName=Dokimopoulos, Email=test@gmail.com, CommunityNickname=Dokimopoulos_0.5703007217718055, Alias=AD0.8, ProfileId=00e5I000000pAGJQA2, EmailEncodingKey=UTF-8, LanguageLocaleKey=en_US, LocaleSidKey=en_US, TimeZoneSidKey=America/Los_Angeles} May 8 '20 at 14:19
0

Rather than passing the entire user object through your error message, you can pass only the username field:

Replace

throw new AuraHandledException('Duplicate username: ' +newCommunitiesUser);

With

throw new AuraHandledException('Duplicate username: ' +newCommunitiesUser.Username);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.