2

I am trying to show the error message from the apex method exception as a toast message while doing imperative call in lwc. I am using ldsUtil.js to simplify the error message. But either way, I am not getting the error message in a toast.

        this.error = reduceErrors(error);
        console.log('error in save :'+error);
        console.log('reduceErrors(error) :'+this.error);

All above 3 lines are printing the error successfully but when I am trying pass reduceErrors(error) or this.error in toast message, the message is coming blank. See screenshot. What am I doing wrong?

    .catch(error =>{
        this.error = reduceErrors(error);
        console.log('error in save :'+error);
        console.log('reduceErrors(error) :'+this.error);
        const event = new ShowToastEvent({
            title: 'Save status',
            message: this.error,
            //message: reduceErrors(error),
            variant: 'error',
        });
        this.dispatchEvent(event);
    });

enter image description here

Imported Modules :

import { LightningElement, wire, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { reduceErrors } from 'c/ldsUtils';
import saveStatus from '@salesforce/apex/MyClass.saveStatus';

ldsUtils Link: https://github.com/trailheadapps/lwc-recipes/tree/main/force-app/main/default/lwc/ldsUtils

4
  • Can you share the modules you have for import? Aug 16 at 13:39
  • @MohithShrivastava Added modules
    – Akash
    Aug 16 at 14:06
  • Can you also share reduceErrors function you have? Aug 16 at 14:19
  • I have provided URL of the reduceErrors js
    – Akash
    Aug 16 at 14:31
1

Try the below to see if this helps

const event = new ShowToastEvent({
                title: 'Save status',
                message: error.body.message,
                variant: 'error'
            });
this.dispatchEvent(event);
2
  • Yes this works but this one is only for body.message . What about if error is present in error.message? For this reason only I am using reduce error function. Can you suggest workaround?
    – Akash
    Aug 17 at 7:27
  • 2
    I am pretty sure that reduce function you have is causing issues. I suggest loop over error object and create a concatenation of all error messages and then use that in your code. Aug 17 at 13:07
0

Finally, it worked. Tried with return value from reduceErrors inside JSON.stringify and it works like a charm even for the custom exceptions thrown using CalloutException.

Apex Custom Error:

    CalloutException e = new CalloutException();
    e.setMessage('Parameters are blank. Please contact your Administrator!');
    throw e;   

LWC Js:

            this.showToastNotice('Product Setup',JSON.stringify(this.error),'error');

enter image description here

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.