0

I have created a validation rule to validate data before insert. It displays error message in debug log, but not able to display on UI of a lightning component.

It gives error like this:

15:30:24:457 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Please choose Pricelist as USD and selling country as India if Posting country is outside India: [PriceList__c]

Please suggest how to display error msg on UI

1 Answer 1

0

You can use an AuraHandledException in your apex class. See the below example.

// Best practice: user-friendly error message provided by an AuraHandledException
@AuraEnabled
public static void triggerBasicAuraHandledError() {
    try {
        integer a = 1 / 0; // Division by zero causes exception
    }
    catch (Exception e) {
        // "Convert" the exception into an AuraHandledException
        throw new AuraHandledException('Darn it! Something went wrong: '
            + e.getMessage());    
    }
    finally {
        // Something executed whether there was an error or not
    }
}

This is how you can handle the AuraHandledException in the component.

function(response) {
    // Checking the server response state
    let state = response.getState();
    if (state === "SUCCESS") {
        // Process server success response
        let returnValue = response.getReturnValue();
    }
    else if (state === "ERROR") {
        // Process error returned by server
        let errors = response.getError();
        let message = 'Unknown error'; // Default error message
        // Retrieve the error message sent by the server
        if (errors && Array.isArray(errors) && errors.length > 0) {
            message = errors[0].message;
        }
        // Display the message
        console.error(message);
    }
    else {
        // Handle other reponse states
    }
}

Refer the detailed information here.

You must log in to answer this question.

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