[SalesForce] Possible Workaround to perform DML when cacheable is true

According to documentation, it is recommended to make wired apex calls from LWC cached, by adding the following annotation to the controller's method:

@AuraEnabled(cacheable=true)

However, adding the "cacheable=true" part also means that the DML limit goes all the way to zero. because:

To improve runtime performance, annotate the Apex method with @AuraEnabled(cacheable=true), which caches the method results on the client. To set cacheable=true, a method must only get data, it can’t mutate (change) data.
To call an Apex method imperatively, you can choose to set cacheable=true. This setting caches the result on the client, and prevents Data Manipulation Language (DML) operations.

The standard structure for us to return data to the client is as follows:

  try {
    //code for returning data to client
 } catch(Exception e) {
   //here code writes a record to the log object , this triggers a DML 
 exception

 }

Now as you can see, whenever there are some exceptions, there is code that tries to write a log record, which then triggers a DMLLimitException!
Is there any solution for it?

Trying to avoid following possible solutions:

  1. Make the error logging code (there is a service class for this)
    asynchronous with @future or queueable
  2. Remove the "Cacheable=true"
    annotation

Best Answer

  1. ) throw the exception in catch block catch(Exception ex) { throw ex. }

2.) Your promise method in js will catch the Exception .error()

3.) Call another APEX method in JS to pass the exception back and use DML statement to insert the exception into Log there.