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);}
Answer
rather than an edit. You can accept another answer if someone else provides something better. But putting the answer in yourQuestion
body is a bit awkward.