0

Before updating a record I want to check a text field is black or not. If the text field is black then only my record is going to update or else I want to throw an Error message in ShowToastEvent.

@AuraEnabled
public static void saveRecord(Id caseId) {
   Case caseRec = [SELECT Id, Checkbox__c, Textfield__c FROM Case WHERE Id = :caseId];
   
   if(String.isNotBlank(caseRec.Textfield__c)){
    throw new AuraHandledException('Unable to update the case as the Textfield is blank.');
   }
   caseRec.Checkbox__c = true;
   update caseRec;
}   

Here I unable to get the error message in UI whereas I can see this AuraHandledException('Unable to update the case.'); in developer Console, But I can see the success message after the record is updated

Javascript

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class CaseUpdate extends LightningElement {

@api recordId;

caseMigration() { 
       saveCaseRec({caseId: this.recordId})
       .then(()=>{
        const evt = new ShowToastEvent({
            title: 'Case updated',
            message: 'Operation sucessful',
            variant: 'success',
            mode: 'dismissable'
        }).catch(error => {this.error = error;});
        this.dispatchEvent(evt);
    });
  }
}

2 Answers 2

3

in your code you're actually checking for not blank in Apex.

I'm using the following method to get the actual error message.

export const getError = (error) => {
  let message = 'Unknown error';
  if (error.body) {
    if (Array.isArray(error.body)) {
      message = error.body.map(e => e.message).join(', ');
    } else if (typeof error.body.message === 'string') {
      message = error.body.message;
    }
  } else {
    message = error.message;
  }

  return message;
}

You can also try using console.error(error) to get the Object of an error.

Hopefully, it will be helpful.

3
  • The catch was in the wrong place...
    – sfdcfox
    Nov 2, 2020 at 16:48
  • I'm blindXD thanks fox
    – ytiq
    Nov 2, 2020 at 22:38
  • Ugh error.body.message instead of error.message - thank you.
    – Shanerk
    Jul 15, 2022 at 17:55
2

Your catch is attached to the ShowToastEvent instead of the then function:

caseMigration() { 
       saveCaseRec({caseId: this.recordId})
       .then(()=>{
        const evt = new ShowToastEvent({
            title: 'Case updated',
            message: 'Operation sucessful',
            variant: 'success',
            mode: 'dismissable'
        })
        this.dispatchEvent(evt);
    }).catch(error => {this.error = error;});;
  }
3
  • Thanks for the quick update. But still, I am unable to get the error message in ShowToastEvent
    – Ryan
    Nov 2, 2020 at 16:56
  • 1
    @Ryan You'd need a separate ShowToastEvent in the catch function.
    – sfdcfox
    Nov 2, 2020 at 17:01
  • Thanks, I got it :)
    – Ryan
    Nov 2, 2020 at 17:02

You must log in to answer this question.

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