5

I call an Apex method statically.

    @AuraEnabled
    public static Id insertx(){
insert new Account();
}

From a LWC component:

insertx().then( () => {})
.catch(error => {this.error = error;})

My problem is that the message returned is: "An internal server error has occurred Error ID: 830852859-43925 (1007478720)"

Anyone knows how to get a proper message from Apex? I also tried using a try/catch and throwing an AuraException but it gave the same result

try{
// a required field is missing
insert new Account();
}
        catch(Exception e){
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, e.getMessage());
            throw new AuraException(e.getMessage());
        }
  • Are you getting a System.LimitException: Too many DML statements: 1 when trying to insert the record? – Renato Oliveira Mar 27 at 11:55
  • @RenatoOliveira I can see its not cacheable, the exception would likely be required field missing – Pranay Jaiswal Mar 27 at 11:56
  • I asked because that's the error I got when trying the exact same logic of inserting an empty account. The error handled by the component is the "internal server error" message, although the Apex code fails because apparently DML operations are not allowed (like if there was a readOnly attribute in a Visualforce page). The method I tried doesn't use cacheable=true, but even if I do use it, the result is the same. – Renato Oliveira Mar 27 at 11:59
  • 1
    @PranayJaiswal See this code: gist.github.com/renatoliveira/885caaf032740881af0ed922eb408623. – Renato Oliveira Mar 27 at 12:07
5

You don't have to throw AuraException, instead, you have to throw AuraHandledException

 @AuraEnabled
    public static string insertAccount(){
        try{
        // a required field is missing
        insert new Account();
        }
        catch(Exception e){

            System.debug(Logginglevel.ERROR, e.getMessage());
            throw new AuraHandledException(e.getMessage());
        }

        return null;
    }

In Console:

{"ok":false,"status":400,"statusText":"Bad Request","body":{"message":"Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account Name]: [Account Name]"}}

Throwing any exception other than AuraHandledException gives internal server error.

  • So the thing is to return a String on the controller method instead of an unsupported type, like Id? Because that’s the only difference I can see between your code and the one on that gist. – Renato Oliveira Mar 27 at 12:27
  • @RenatoOliveira check my comments on your gist – Pranay Jaiswal Mar 27 at 12:28
  • Just did. Thanks for the clarification! – Renato Oliveira Mar 27 at 12:28

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.