2

Hope you're doing well.

I want to print an error toast, the pop-up appearing but the message is not printing.

I researched and tried a lot about that but was unsuccessful.

Below is my JS controller.

import { ShowToastEvent } from 'lightning/platformShowToastEvent';
handleTimesheet() {
    saveData({
        firstName :this.firstName,
        lastName :this.lastName,
        accountId :this.recordId
    })
    .then(result => {
        //Shows Success Toast Event
        const e = new ShowToastEvent({
            title: 'Success',
            message: result,
            variant: 'success',
            mode: 'dismissable',
        });
        this.dispatchEvent(e);
        // console.log('result: ' +result);
    })
    .catch(error => {
        //Shows Error Toast Event
        const e = new ShowToastEvent({
            title: 'Error Occured',
            message: error.body.message,
            // I TRIED THIS AND THE BELOW LINE AS WELL
            message: error.body.output.errors[0].message,
            // I GOT ERROR ON THIS LINE "Cannot read properties of undefined (reading 'errors')"
            variant: 'error',
            mode: 'dismissable',
        });
        this.dispatchEvent(e);
        console.log('Error: ', JSON.stringify(error));
    })
}

Any help would be appreciated.

6
  • Have you tried using message: err.message?
    – TSmith
    Jan 6, 2022 at 16:46
  • err not defined and toast pop-up is also not appearing Jan 6, 2022 at 17:09
  • Sorry I meant message: error.message
    – TSmith
    Jan 6, 2022 at 17:15
  • yes, I tried it first. it doesn't show message on error toast. And I tried message: error as well. Jan 6, 2022 at 17:17
  • Do the console.log messages give the expected output? Jan 6, 2022 at 19:24

2 Answers 2

1

A good place to start, as Victor Lockwood suggests, is to also output to the JavaScript console to see what sort of data you are getting in your error variable:

.catch(error => {
    console.log(JSON.stringify(error));
    ...

Looking at e.g. reduceErrors referenced in the Handle Server Errors Trailhead there are quite a few possibilities; you could consider re-using that code if your case matches one of those.

(Unfortunately the simple "catch all" approach of using JSON.stringify(error) as the toast message typically fails because the JSON curly braces are interpreted as formatting delimiters - the {0} style ones - and that means most of the content isn't rendered.)

0

I was able to solve this problem after doing some research.

Just created another class for Custom Exception and used that custom exception in my main apex classes methods. Below i have pasted the link

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_exception_custom.htm

You must log in to answer this question.

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