0

On my lightning component I have function that calls to server side function to create a case

Controller.apxc

public class CommunityCaseFormController {

    @AuraEnabled
    public static Id createCase(Case c) {
        try {
            insert c;
        } catch (Exception e) {
            String message = e.getMessage();
            AuraHandledException auraError = new AuraHandledException(message);
            auraError.setMessage(message);
            throw auraError;                
        }

        return c.Id;
    }
}

I'm getting an error message because an admin created a validation rule for cases on creation. The response.getError()[0].message from calling the server function has the error message that is in the validation rule, but is has bunch of extra stuff that the user doesn't need to see, such as.

Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION,

.: [Priority]

I could use JavaScript to manipulate the string, but in my opinion that shouldn't be required. How do I get my server-side function to return a cleaner error message?

1

You can use DMLException first to handle these errors, and this class has getDmlMessage method to get the proper validation error message.
So in your case, to get the proper message you can write:

try {
    insert c;
} catch (DMLException de) {
    String message = e.getDmlMessage(0);
    //further code
} catch (Exception e) {
    //any other exception handling
}

in getDmlMessage(0) method, 0 is the row number, in your case there is just one object. You can check the reference-
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_exception_methods.htm

0

I've seen the answer where you get the 0th message from the DmlException, but it does have the disadvantage that if there are multiple rows, it will only return errors about the first.

DmlException is relatively well handled by Aura, so I just rethrow it e.g.

    Savepoint savepoint = Database.setSavepoint();

    try {
        // Do my action
    } catch(DmlException e) {
        Database.rollback(savepoint);
        throw e;
    } catch(AnotherException e) {
        // Catch any other exceptions that could use special treatment
    } catch(Exception e) {
        Database.rollback(savepoint);
        throw new AuraHandledException(e.getMessage() + e.getStackTraceString());
    }

This actually results in an error object that you can deal with in Aura to give a nice user-readable message without having to chop up strings.

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.