7

Let's say I have an apex method like such:

@AuraEnabled
public static void myMethod(String myString){
    if (String.isBlank(myString)) {
        throw new AuraHandledException('Not Cool Bro.');
    }
}

and I have a Lightning Web Component with controller with a method like this:

import myMethod from '@salesforce/apex/MyClass.myMethod';

export default class YeOldeWebComponent extends LightningElement {
    @track myString;

callMyMethod() {
    console.log("Starting my method...");
    myMethod({myString: this.myString})
    .then(() => {
        console.log("My Method Was Successful!");
    })
    .catch(error => {
        console.log("My Method Was Not Successful :/");
        console.log(JSON.stringify(error));
        let myMessage = "Default Error Message.";
        this.showToast("Error!", myMessage , "error");
    });
}    
showToast(theTitle, theMessage, theVariant) {
                const event = new ShowToastEvent({
                    title: theTitle,
                    message: theMessage,
                    variant: theVariant
                });
                this.dispatchEvent(event);
            }

How do I get something useful (the original error message) out of the 'error' variable to pass to the showToast method?

------EDIT ------ I figured it out... it goes a little something like this:

.catch(error => {
        let errorMessage = TOAST_MESSAGE_ERROR;
        if ( error.body.message) {
            errorMessage =error.body.message;
        }
        this.showToast(TOAST_TITLE_ERROR, errorMessage, TOAST_VARIANT_ERROR);}
1
  • 4
    Hi Mitch, not sure if you've read How to Ask and How to Answer before, but they may be worth a quick read. Please post your discovery as an Answer rather than an edit. You can accept another answer if someone else provides something better. But putting the answer in your Question body is a bit awkward.
    – Adrian Larson
    Commented Mar 15, 2019 at 21:24

1 Answer 1

13

Got it figured out - it looks like this!

.catch(error => {
    let errorMessage = TOAST_MESSAGE_ERROR;
    if ( error.body.message) {
        errorMessage =error.body.message;
    }
    this.showToast(TOAST_TITLE_ERROR, errorMessage, TOAST_VARIANT_ERROR);}

You must log in to answer this question.

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