-1

I have an Apex method that receives an Account record as input and returns Account record. What if an error occurs and i want to return it to the user? I cannot return String, since the method returns Account. Any ideas ?

  • 3
    Sounds like the concept you're looking for is exceptions, but we'll need more details if you want an accurate answer. Probably the most important detail here is how does the user end up calling this apex method? Is it called as part of a trigger, a visualforce page or lightning component, or something else? – Derek F Sep 19 '19 at 11:14
  • Hi Derek,For example: @AuraEnabled public static List<String> matchingService(Account acc) { try{//Some code here and return acc; } catch (Exception e){ return ('The following exception has occurred: ' + e.getMessage()) I cannot save this method cause i cannot return a string. – Giorgos Galaios Sep 19 '19 at 12:36
0

Based on your comment, you are looking for a way to return custom error message to User in your Lightning Component. One solution would be to use AuraHandledException in your Apex controller. Then you can throw this exception and pass String argument to helper which will display it to the User.

Apex controller:

@AuraEnabled public static List<String> matchingService(Account acc) {
    List<String> returnList = new List<String>();
    try {
    //perform some logic on returnList
    } catch (Exception ex) {
        throw new AuraHandledException('You cannot perform this action, error occured: ' + ex.getMessage);
    } 
    return returnList;

}

JS Helper:

myFunction: function (component, account) {
        var action = component.get("c.matchingService");
        var account;

        action.setParams({
            "acc": account,
        });

        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var stringList = response.getReturnValue();
            } else {
                //errorMessage is the String argument of AuraHandledException
                var errorMessage = response.getError()[0].message;
                console.log('Error in matchingService : ' + errorMessage);

                //Handle error - for example show toast with message from Apex controller
                helper.showToast(component, errorMessage);
            }

        });
        $A.enqueueAction(action);
    }

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.