Lightning Web Components – Unable to Print Error Toast Message

lightning-web-componentstoast

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.

Best Answer

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.)

Related Topic