How to Aura Handle multiple DmlExceptions Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) 2019 Community Moderator Election ResultsHow to show exception message in lightning without stacktrace?How to rethrow DmlExceptions as AuraHandledExceptions rightCan I throw an exception in apex and still log the caught exception?Handle exception in managed packageHow to update a field with Lightning Components?fault string: No such parameter param defined for the operation, please check the WSDL for the serviceAura StaticResource Javascript helper classesLockerService and D3 version 4 causing random Promise error in ltng:requireCant catch exception and log to custom object if I throw exceptionDid Salesforce recently update their aura library? Facing weird issues with access control and string concatenationHandle errors in visualforce table with multiple checkboxHow to rethrow DmlExceptions as AuraHandledExceptions right

.bashrc alias for a command with fixed second parameter

How do Java 8 default methods hеlp with lambdas?

"Destructive power" carried by a B-52?

Found this skink in my tomato plant bucket. Is he trapped? Or could he leave if he wanted?

What criticisms of Wittgenstein's philosophy of language have been offered?

Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?

Is the time—manner—place ordering of adverbials an oversimplification?

Was the pager message from Nick Fury to Captain Marvel unnecessary?

Where and when has Thucydides been studied?

What was the last profitable war?

Flight departed from the gate 5 min before scheduled departure time. Refund options

Russian equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

How does the body cool itself in a stillsuit?

Is the Mordenkainen's Sword spell underpowered?

What are some likely causes to domain member PC losing contact to domain controller?

When does a function NOT have an antiderivative?

Does the main washing effect of soap come from foam?

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

What is the proper term for etching or digging of wall to hide conduit of cables

Fit odd number of triplets in a measure?

The Nth Gryphon Number

My mentor says to set image to Fine instead of RAW — how is this different from JPG?

newbie Q : How to read an output file in one command line

Did any compiler fully use 80-bit floating point?



How to Aura Handle multiple DmlExceptions



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
2019 Community Moderator Election ResultsHow to show exception message in lightning without stacktrace?How to rethrow DmlExceptions as AuraHandledExceptions rightCan I throw an exception in apex and still log the caught exception?Handle exception in managed packageHow to update a field with Lightning Components?fault string: No such parameter param defined for the operation, please check the WSDL for the serviceAura StaticResource Javascript helper classesLockerService and D3 version 4 causing random Promise error in ltng:requireCant catch exception and log to custom object if I throw exceptionDid Salesforce recently update their aura library? Facing weird issues with access control and string concatenationHandle errors in visualforce table with multiple checkboxHow to rethrow DmlExceptions as AuraHandledExceptions right



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















How should I handle multiple DmlException messages when using AuraHandledException inside an Apex Controller.



If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getMessage());
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message, that the users won't like.




System.DmlException: Update failed. First exception on row 0 with id a0220000005vt34AAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION: bla bla bla




If I do this:



try 
upsert value;
catch(DmlException e)
throw e;
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message which is even worse:




Unknown Error




If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getDmlMessage(0));
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I only get 1 of the DML errors and there could be many.



On the client-side I am using this JavaScript code to call controller actions and handle errors:



callAction: function (cmp, methodName, params, callback) 
var action = cmp.get(methodName);
action.setParams(params);
action.setCallback(this, function (response)
var state = response.getState();
if (cmp.isValid() && state === 'SUCCESS')
var result = response.getReturnValue();
if (callback) callback(result);
else if (state === 'ERROR')
this.handleErrors(cmp, response.getError());

);
$A.getCallback(function ()
$A.enqueueAction(action);
)();
,
handleErrors: function (cmp, errors)
let toastParams =
title: 'Error',
message: 'Unknown error',
type: 'error'
;
if (errors)
if (errors[0] && errors[0].message)
console.log(errors[0].message);
toastParams.message = errors[0].message;


let toastEvent = $A.get('e.force:showToast');
toastEvent.setParams(toastParams);
toastEvent.fire();
,


I cannot find the defacto solution or framework best practice for handling what must be a common scenario.



Ideally, I'd like a solution which can be used in the Apex controller.



Questions



  1. Is there a capability built into the Lightning framework to handle multiple DmlException's?

  2. Should the JavaScript handle the DmlException rethrow differently?

  3. Do I need to write some custom Apex to handle multiple DmlException's?

--



NOTE: this is not a duplicate of this question because he never got a satisfactory answer.










share|improve this question
























  • Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

    – Raul
    Apr 4 at 9:34












  • @Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

    – Robs
    Apr 4 at 9:53












  • I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

    – javanoob
    Apr 4 at 13:29






  • 1





    Maybe we can do this all on the client side(JavaScript).

    – itzmukeshy7
    Apr 4 at 13:51

















7















How should I handle multiple DmlException messages when using AuraHandledException inside an Apex Controller.



If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getMessage());
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message, that the users won't like.




System.DmlException: Update failed. First exception on row 0 with id a0220000005vt34AAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION: bla bla bla




If I do this:



try 
upsert value;
catch(DmlException e)
throw e;
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message which is even worse:




Unknown Error




If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getDmlMessage(0));
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I only get 1 of the DML errors and there could be many.



On the client-side I am using this JavaScript code to call controller actions and handle errors:



callAction: function (cmp, methodName, params, callback) 
var action = cmp.get(methodName);
action.setParams(params);
action.setCallback(this, function (response)
var state = response.getState();
if (cmp.isValid() && state === 'SUCCESS')
var result = response.getReturnValue();
if (callback) callback(result);
else if (state === 'ERROR')
this.handleErrors(cmp, response.getError());

);
$A.getCallback(function ()
$A.enqueueAction(action);
)();
,
handleErrors: function (cmp, errors)
let toastParams =
title: 'Error',
message: 'Unknown error',
type: 'error'
;
if (errors)
if (errors[0] && errors[0].message)
console.log(errors[0].message);
toastParams.message = errors[0].message;


let toastEvent = $A.get('e.force:showToast');
toastEvent.setParams(toastParams);
toastEvent.fire();
,


I cannot find the defacto solution or framework best practice for handling what must be a common scenario.



Ideally, I'd like a solution which can be used in the Apex controller.



Questions



  1. Is there a capability built into the Lightning framework to handle multiple DmlException's?

  2. Should the JavaScript handle the DmlException rethrow differently?

  3. Do I need to write some custom Apex to handle multiple DmlException's?

--



NOTE: this is not a duplicate of this question because he never got a satisfactory answer.










share|improve this question
























  • Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

    – Raul
    Apr 4 at 9:34












  • @Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

    – Robs
    Apr 4 at 9:53












  • I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

    – javanoob
    Apr 4 at 13:29






  • 1





    Maybe we can do this all on the client side(JavaScript).

    – itzmukeshy7
    Apr 4 at 13:51













7












7








7


3






How should I handle multiple DmlException messages when using AuraHandledException inside an Apex Controller.



If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getMessage());
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message, that the users won't like.




System.DmlException: Update failed. First exception on row 0 with id a0220000005vt34AAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION: bla bla bla




If I do this:



try 
upsert value;
catch(DmlException e)
throw e;
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message which is even worse:




Unknown Error




If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getDmlMessage(0));
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I only get 1 of the DML errors and there could be many.



On the client-side I am using this JavaScript code to call controller actions and handle errors:



callAction: function (cmp, methodName, params, callback) 
var action = cmp.get(methodName);
action.setParams(params);
action.setCallback(this, function (response)
var state = response.getState();
if (cmp.isValid() && state === 'SUCCESS')
var result = response.getReturnValue();
if (callback) callback(result);
else if (state === 'ERROR')
this.handleErrors(cmp, response.getError());

);
$A.getCallback(function ()
$A.enqueueAction(action);
)();
,
handleErrors: function (cmp, errors)
let toastParams =
title: 'Error',
message: 'Unknown error',
type: 'error'
;
if (errors)
if (errors[0] && errors[0].message)
console.log(errors[0].message);
toastParams.message = errors[0].message;


let toastEvent = $A.get('e.force:showToast');
toastEvent.setParams(toastParams);
toastEvent.fire();
,


I cannot find the defacto solution or framework best practice for handling what must be a common scenario.



Ideally, I'd like a solution which can be used in the Apex controller.



Questions



  1. Is there a capability built into the Lightning framework to handle multiple DmlException's?

  2. Should the JavaScript handle the DmlException rethrow differently?

  3. Do I need to write some custom Apex to handle multiple DmlException's?

--



NOTE: this is not a duplicate of this question because he never got a satisfactory answer.










share|improve this question
















How should I handle multiple DmlException messages when using AuraHandledException inside an Apex Controller.



If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getMessage());
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message, that the users won't like.




System.DmlException: Update failed. First exception on row 0 with id a0220000005vt34AAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION: bla bla bla




If I do this:



try 
upsert value;
catch(DmlException e)
throw e;
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I get an unfriendly error message which is even worse:




Unknown Error




If I do this:



try 
upsert value;
catch(DmlException e)
throw new AuraHandledException(e.getDmlMessage(0));
catch(Exception e)
throw new AuraHandledException(e.getMessage());



I only get 1 of the DML errors and there could be many.



On the client-side I am using this JavaScript code to call controller actions and handle errors:



callAction: function (cmp, methodName, params, callback) 
var action = cmp.get(methodName);
action.setParams(params);
action.setCallback(this, function (response)
var state = response.getState();
if (cmp.isValid() && state === 'SUCCESS')
var result = response.getReturnValue();
if (callback) callback(result);
else if (state === 'ERROR')
this.handleErrors(cmp, response.getError());

);
$A.getCallback(function ()
$A.enqueueAction(action);
)();
,
handleErrors: function (cmp, errors)
let toastParams =
title: 'Error',
message: 'Unknown error',
type: 'error'
;
if (errors)
if (errors[0] && errors[0].message)
console.log(errors[0].message);
toastParams.message = errors[0].message;


let toastEvent = $A.get('e.force:showToast');
toastEvent.setParams(toastParams);
toastEvent.fire();
,


I cannot find the defacto solution or framework best practice for handling what must be a common scenario.



Ideally, I'd like a solution which can be used in the Apex controller.



Questions



  1. Is there a capability built into the Lightning framework to handle multiple DmlException's?

  2. Should the JavaScript handle the DmlException rethrow differently?

  3. Do I need to write some custom Apex to handle multiple DmlException's?

--



NOTE: this is not a duplicate of this question because he never got a satisfactory answer.







apex lightning-aura-components lightning exception dmlexception






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 4 at 9:02







Robs

















asked Apr 4 at 7:33









RobsRobs

2,511642




2,511642












  • Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

    – Raul
    Apr 4 at 9:34












  • @Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

    – Robs
    Apr 4 at 9:53












  • I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

    – javanoob
    Apr 4 at 13:29






  • 1





    Maybe we can do this all on the client side(JavaScript).

    – itzmukeshy7
    Apr 4 at 13:51

















  • Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

    – Raul
    Apr 4 at 9:34












  • @Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

    – Robs
    Apr 4 at 9:53












  • I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

    – javanoob
    Apr 4 at 13:29






  • 1





    Maybe we can do this all on the client side(JavaScript).

    – itzmukeshy7
    Apr 4 at 13:51
















Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

– Raul
Apr 4 at 9:34






Could you not iterate over e.getDmlMessage to throw all errors in a loop or concatenate them?

– Raul
Apr 4 at 9:34














@Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

– Robs
Apr 4 at 9:53






@Raul obviously I could. I am enquiring to see if there are is a standard platform feature or a high quality solution out there.

– Robs
Apr 4 at 9:53














I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

– javanoob
Apr 4 at 13:29





I kind of ran into same issue and resorted to regular expression route. salesforce.stackexchange.com/questions/226338/… If the exception is thrown from deep inside helper class or somewhere then AuraHandledException doesn't work as expected and spits out ugly exception.

– javanoob
Apr 4 at 13:29




1




1





Maybe we can do this all on the client side(JavaScript).

– itzmukeshy7
Apr 4 at 13:51





Maybe we can do this all on the client side(JavaScript).

– itzmukeshy7
Apr 4 at 13:51










3 Answers
3






active

oldest

votes


















3














I would think of using Database.upsert() method which returns Database.UpsertResult[] where error messages can be collected and pass that to AuraHandledException.



You can capture all the errors together which you are facing issues above.



Database methods provide more flexibility that using straight DML statements.



try 
List<String> lstErrorMsg = new List<String>();
Database.UpsertResult[] results = Database.upsert(value,false);
if (results != null)
for (Database.UpsertResult result : results)
if (!result.isSuccess())
Database.Error[] errs = result.getErrors();
for(Database.Error err : errs)

lstErrorMsg.add(err.getMessage());



if(lstErrorMsg.size()>0)
throw new AuraHandledException(lstErrorMsg);


catch (Exception e)
throw new AuraHandledException(e.getMessage());



You can also think of using custom error message comparing the DMLException related errors and show it to the users, because system thrown DMLExceptions are unfriendly user messages.



You could create own framework and Utility classes to handle exceptions and reusing the above script.






share|improve this answer

























  • Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

    – Robs
    Apr 4 at 9:00












  • I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

    – Santanu Boral
    Apr 4 at 9:03












  • I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

    – Robs
    Apr 4 at 9:27











  • Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

    – Robs
    Apr 4 at 9:30



















2














These errors we can handle in the JavaScript part, and also for the Apex side as well we can do write some utility methods.



So inside the callback, we can parse the error we got from the server.
For the same, sharing what I do use for the same, feel free to share your thoughts.



AuraBase lightning component and an apex class to handle all the background things parsing the response/errors and also logging errors/exceptions as needed in database/email.



handleErrors: function (c, errors) 
var h = this;

if (errors && Array.isArray(errors))
var errorMessages = [];
errors.forEach(function (error) '';
/* Add more statuses here that you want to parse, if you provide the value then it will show that value directly, instead of parsing the error, else it will format the error and will show to the user. */
var statusCodes =
'CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY': '',
'ENTITY_IS_DELETED': ''
;

var statusKeys = Object.keys(statusCodes);
for (var statusCode = 0, totalCodes = statusKeys.length; statusCode < totalCodes; statusCode++)
try
if (message.indexOf(statusKeys[statusCode]) > -1)
if (!statusCodes[statusKeys[statusCode]])
message = message.split(statusKeys[statusCode] + ', ')[1];
var messageParts = message.split(': ');
if (messageParts.length > 1)
messageParts.pop();

message = messageParts.join(': ');
else
message = statusCodes[statusKeys[statusCode]];

break;

catch (statusCodeException)
break;


errorMessages.push(message);
);

if (errorMessages.length > 0)
h.warning(errorMessages.join(', '), mode: 'sticky' );

else
h.warning('Something went wrong.', mode: 'sticky', title: 'Contact System Administrator!' );




And on the Apex side, we can use try...catch() to handle the exceptions and the JS part will handle all the errors 0/1/N.



try
Integer anError = 1/0;
catch(Exception e)
throw new AuraHandledException(e);






share|improve this answer
































    1














    A purely Apex solution would be to have a AuraHandledExceptionFactory which creates the AuraHandledException with a correctly formatted error message based on the Exception type it was caught.



    Apex Controller



    Simple one line usage



    public with sharing class ApexController 

    @AuraEnabled
    public static String getAction()

    try
    // do something
    catch (Exception cause)
    throw AuraHandledExceptionFactory.create(cause);





    AuraHandledExceptionFactory



    Factory pattern used to generate the aproprate ExceptionHandler based on the type of Exception that has been provided.



    public class AuraHandledExceptionFactory 

    public static AuraHandledException create(Exception cause)
    Type handlerType = getType(cause);
    ExceptionHandler handler = newInstance(handlerType);
    return new AuraHandledException(handler.getMessage(cause));


    private static ExceptionHandler newInstance(Type handlerType)
    try
    return (ExceptionHandler) handlerType.newInstance();
    catch (Exception ignore)
    return new ExceptionHandler();



    private static Type getType(Exception cause)
    return Type.forName(getTypeName(cause));


    private static String getTypeName(Exception cause)
    return cause.getTypeName() + 'Handler';




    ExceptionHandler



    This virtual class can extended for different Exception types



    public virtual class ExceptionHandler 
    public virtual String getMessage(Exception cause)
    return cause.getMessage();




    DmlExceptionHandler



    A custom implementation to handle the DmlException type.



    public class DmlExceptionHandler extends ExceptionHandler 

    public override String getMessage(Exception cause)

    DmlException dml = (DmlException) cause;

    String message = '';

    for(integer index = 0; index < dml.getNumDML(); index++)
    // simple implementation
    message += dml.getDmlMessage(index);

    return message;




    This approach follows the Single Responsibility Principle and the Open-Closed Principle by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.



    Single Responsibility Principle




    The single responsibility principle is that states that every class
    should have responsibility over a single part of the functionality
    provided by the software, and that responsibility should be entirely
    encapsulated by the class.




    Open-Closed Principle




    The open-closed principle states classes should be open for extension,
    but closed for modification; that is, such an entity can allow its
    behaviour to be extended without modifying its source code.







    share|improve this answer

























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "459"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f256531%2fhow-to-aura-handle-multiple-dmlexceptions%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      I would think of using Database.upsert() method which returns Database.UpsertResult[] where error messages can be collected and pass that to AuraHandledException.



      You can capture all the errors together which you are facing issues above.



      Database methods provide more flexibility that using straight DML statements.



      try 
      List<String> lstErrorMsg = new List<String>();
      Database.UpsertResult[] results = Database.upsert(value,false);
      if (results != null)
      for (Database.UpsertResult result : results)
      if (!result.isSuccess())
      Database.Error[] errs = result.getErrors();
      for(Database.Error err : errs)

      lstErrorMsg.add(err.getMessage());



      if(lstErrorMsg.size()>0)
      throw new AuraHandledException(lstErrorMsg);


      catch (Exception e)
      throw new AuraHandledException(e.getMessage());



      You can also think of using custom error message comparing the DMLException related errors and show it to the users, because system thrown DMLExceptions are unfriendly user messages.



      You could create own framework and Utility classes to handle exceptions and reusing the above script.






      share|improve this answer

























      • Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

        – Robs
        Apr 4 at 9:00












      • I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

        – Santanu Boral
        Apr 4 at 9:03












      • I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

        – Robs
        Apr 4 at 9:27











      • Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

        – Robs
        Apr 4 at 9:30
















      3














      I would think of using Database.upsert() method which returns Database.UpsertResult[] where error messages can be collected and pass that to AuraHandledException.



      You can capture all the errors together which you are facing issues above.



      Database methods provide more flexibility that using straight DML statements.



      try 
      List<String> lstErrorMsg = new List<String>();
      Database.UpsertResult[] results = Database.upsert(value,false);
      if (results != null)
      for (Database.UpsertResult result : results)
      if (!result.isSuccess())
      Database.Error[] errs = result.getErrors();
      for(Database.Error err : errs)

      lstErrorMsg.add(err.getMessage());



      if(lstErrorMsg.size()>0)
      throw new AuraHandledException(lstErrorMsg);


      catch (Exception e)
      throw new AuraHandledException(e.getMessage());



      You can also think of using custom error message comparing the DMLException related errors and show it to the users, because system thrown DMLExceptions are unfriendly user messages.



      You could create own framework and Utility classes to handle exceptions and reusing the above script.






      share|improve this answer

























      • Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

        – Robs
        Apr 4 at 9:00












      • I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

        – Santanu Boral
        Apr 4 at 9:03












      • I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

        – Robs
        Apr 4 at 9:27











      • Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

        – Robs
        Apr 4 at 9:30














      3












      3








      3







      I would think of using Database.upsert() method which returns Database.UpsertResult[] where error messages can be collected and pass that to AuraHandledException.



      You can capture all the errors together which you are facing issues above.



      Database methods provide more flexibility that using straight DML statements.



      try 
      List<String> lstErrorMsg = new List<String>();
      Database.UpsertResult[] results = Database.upsert(value,false);
      if (results != null)
      for (Database.UpsertResult result : results)
      if (!result.isSuccess())
      Database.Error[] errs = result.getErrors();
      for(Database.Error err : errs)

      lstErrorMsg.add(err.getMessage());



      if(lstErrorMsg.size()>0)
      throw new AuraHandledException(lstErrorMsg);


      catch (Exception e)
      throw new AuraHandledException(e.getMessage());



      You can also think of using custom error message comparing the DMLException related errors and show it to the users, because system thrown DMLExceptions are unfriendly user messages.



      You could create own framework and Utility classes to handle exceptions and reusing the above script.






      share|improve this answer















      I would think of using Database.upsert() method which returns Database.UpsertResult[] where error messages can be collected and pass that to AuraHandledException.



      You can capture all the errors together which you are facing issues above.



      Database methods provide more flexibility that using straight DML statements.



      try 
      List<String> lstErrorMsg = new List<String>();
      Database.UpsertResult[] results = Database.upsert(value,false);
      if (results != null)
      for (Database.UpsertResult result : results)
      if (!result.isSuccess())
      Database.Error[] errs = result.getErrors();
      for(Database.Error err : errs)

      lstErrorMsg.add(err.getMessage());



      if(lstErrorMsg.size()>0)
      throw new AuraHandledException(lstErrorMsg);


      catch (Exception e)
      throw new AuraHandledException(e.getMessage());



      You can also think of using custom error message comparing the DMLException related errors and show it to the users, because system thrown DMLExceptions are unfriendly user messages.



      You could create own framework and Utility classes to handle exceptions and reusing the above script.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Apr 4 at 9:07

























      answered Apr 4 at 8:47









      Santanu BoralSantanu Boral

      31.4k52456




      31.4k52456












      • Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

        – Robs
        Apr 4 at 9:00












      • I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

        – Santanu Boral
        Apr 4 at 9:03












      • I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

        – Robs
        Apr 4 at 9:27











      • Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

        – Robs
        Apr 4 at 9:30


















      • Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

        – Robs
        Apr 4 at 9:00












      • I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

        – Santanu Boral
        Apr 4 at 9:03












      • I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

        – Robs
        Apr 4 at 9:27











      • Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

        – Robs
        Apr 4 at 9:30

















      Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

      – Robs
      Apr 4 at 9:00






      Thanks for responding and providing a solution. But surely you're not suggesting that everyone include 15 lines of code in every method to handle this? Also, this solution doesn't work if the insert/update is inside business logic which gets used by another part of the system which is not a lightning component, which often is the case i.e. a Service class which is used by a Queuable and InvocableMethod and a Lightning Component

      – Robs
      Apr 4 at 9:00














      I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

      – Santanu Boral
      Apr 4 at 9:03






      I don't suggest to write 15 lines of code, rather I would prepare to create utility class to use this script as a method. Can you elaborate this line "Also, this solution doesn't work if the insert/update is inside business logic which gets consumed something than a lightning component, which often is the case"? You need to create your own framework to handle relevant exceptions.

      – Santanu Boral
      Apr 4 at 9:03














      I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

      – Robs
      Apr 4 at 9:27





      I've updated my previous comment. In-addition: it's not always the case that you are doing the DML action in a controller, so throwing an AuraHandledException deep in your business logic would be bad practice. No offence, but I find this to be a low quality solution/answer to what must be a common problem, so there must be more standardise solutions... I could have whipped together some code the puts the errors into a list...

      – Robs
      Apr 4 at 9:27













      Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

      – Robs
      Apr 4 at 9:30






      Also, is the answer a utility class or a custom exception based on DmlException or is there a platform solution or is it something else. If you are suggesting a utility class, why don't you provide one rather than a block of hacked together code which has very little use to the community in the future. Whereas, providing a utility class would help everyone who visits which page in the future...

      – Robs
      Apr 4 at 9:30














      2














      These errors we can handle in the JavaScript part, and also for the Apex side as well we can do write some utility methods.



      So inside the callback, we can parse the error we got from the server.
      For the same, sharing what I do use for the same, feel free to share your thoughts.



      AuraBase lightning component and an apex class to handle all the background things parsing the response/errors and also logging errors/exceptions as needed in database/email.



      handleErrors: function (c, errors) 
      var h = this;

      if (errors && Array.isArray(errors))
      var errorMessages = [];
      errors.forEach(function (error) '';
      /* Add more statuses here that you want to parse, if you provide the value then it will show that value directly, instead of parsing the error, else it will format the error and will show to the user. */
      var statusCodes =
      'CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY': '',
      'ENTITY_IS_DELETED': ''
      ;

      var statusKeys = Object.keys(statusCodes);
      for (var statusCode = 0, totalCodes = statusKeys.length; statusCode < totalCodes; statusCode++)
      try
      if (message.indexOf(statusKeys[statusCode]) > -1)
      if (!statusCodes[statusKeys[statusCode]])
      message = message.split(statusKeys[statusCode] + ', ')[1];
      var messageParts = message.split(': ');
      if (messageParts.length > 1)
      messageParts.pop();

      message = messageParts.join(': ');
      else
      message = statusCodes[statusKeys[statusCode]];

      break;

      catch (statusCodeException)
      break;


      errorMessages.push(message);
      );

      if (errorMessages.length > 0)
      h.warning(errorMessages.join(', '), mode: 'sticky' );

      else
      h.warning('Something went wrong.', mode: 'sticky', title: 'Contact System Administrator!' );




      And on the Apex side, we can use try...catch() to handle the exceptions and the JS part will handle all the errors 0/1/N.



      try
      Integer anError = 1/0;
      catch(Exception e)
      throw new AuraHandledException(e);






      share|improve this answer





























        2














        These errors we can handle in the JavaScript part, and also for the Apex side as well we can do write some utility methods.



        So inside the callback, we can parse the error we got from the server.
        For the same, sharing what I do use for the same, feel free to share your thoughts.



        AuraBase lightning component and an apex class to handle all the background things parsing the response/errors and also logging errors/exceptions as needed in database/email.



        handleErrors: function (c, errors) 
        var h = this;

        if (errors && Array.isArray(errors))
        var errorMessages = [];
        errors.forEach(function (error) '';
        /* Add more statuses here that you want to parse, if you provide the value then it will show that value directly, instead of parsing the error, else it will format the error and will show to the user. */
        var statusCodes =
        'CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY': '',
        'ENTITY_IS_DELETED': ''
        ;

        var statusKeys = Object.keys(statusCodes);
        for (var statusCode = 0, totalCodes = statusKeys.length; statusCode < totalCodes; statusCode++)
        try
        if (message.indexOf(statusKeys[statusCode]) > -1)
        if (!statusCodes[statusKeys[statusCode]])
        message = message.split(statusKeys[statusCode] + ', ')[1];
        var messageParts = message.split(': ');
        if (messageParts.length > 1)
        messageParts.pop();

        message = messageParts.join(': ');
        else
        message = statusCodes[statusKeys[statusCode]];

        break;

        catch (statusCodeException)
        break;


        errorMessages.push(message);
        );

        if (errorMessages.length > 0)
        h.warning(errorMessages.join(', '), mode: 'sticky' );

        else
        h.warning('Something went wrong.', mode: 'sticky', title: 'Contact System Administrator!' );




        And on the Apex side, we can use try...catch() to handle the exceptions and the JS part will handle all the errors 0/1/N.



        try
        Integer anError = 1/0;
        catch(Exception e)
        throw new AuraHandledException(e);






        share|improve this answer



























          2












          2








          2







          These errors we can handle in the JavaScript part, and also for the Apex side as well we can do write some utility methods.



          So inside the callback, we can parse the error we got from the server.
          For the same, sharing what I do use for the same, feel free to share your thoughts.



          AuraBase lightning component and an apex class to handle all the background things parsing the response/errors and also logging errors/exceptions as needed in database/email.



          handleErrors: function (c, errors) 
          var h = this;

          if (errors && Array.isArray(errors))
          var errorMessages = [];
          errors.forEach(function (error) '';
          /* Add more statuses here that you want to parse, if you provide the value then it will show that value directly, instead of parsing the error, else it will format the error and will show to the user. */
          var statusCodes =
          'CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY': '',
          'ENTITY_IS_DELETED': ''
          ;

          var statusKeys = Object.keys(statusCodes);
          for (var statusCode = 0, totalCodes = statusKeys.length; statusCode < totalCodes; statusCode++)
          try
          if (message.indexOf(statusKeys[statusCode]) > -1)
          if (!statusCodes[statusKeys[statusCode]])
          message = message.split(statusKeys[statusCode] + ', ')[1];
          var messageParts = message.split(': ');
          if (messageParts.length > 1)
          messageParts.pop();

          message = messageParts.join(': ');
          else
          message = statusCodes[statusKeys[statusCode]];

          break;

          catch (statusCodeException)
          break;


          errorMessages.push(message);
          );

          if (errorMessages.length > 0)
          h.warning(errorMessages.join(', '), mode: 'sticky' );

          else
          h.warning('Something went wrong.', mode: 'sticky', title: 'Contact System Administrator!' );




          And on the Apex side, we can use try...catch() to handle the exceptions and the JS part will handle all the errors 0/1/N.



          try
          Integer anError = 1/0;
          catch(Exception e)
          throw new AuraHandledException(e);






          share|improve this answer















          These errors we can handle in the JavaScript part, and also for the Apex side as well we can do write some utility methods.



          So inside the callback, we can parse the error we got from the server.
          For the same, sharing what I do use for the same, feel free to share your thoughts.



          AuraBase lightning component and an apex class to handle all the background things parsing the response/errors and also logging errors/exceptions as needed in database/email.



          handleErrors: function (c, errors) 
          var h = this;

          if (errors && Array.isArray(errors))
          var errorMessages = [];
          errors.forEach(function (error) '';
          /* Add more statuses here that you want to parse, if you provide the value then it will show that value directly, instead of parsing the error, else it will format the error and will show to the user. */
          var statusCodes =
          'CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY': '',
          'ENTITY_IS_DELETED': ''
          ;

          var statusKeys = Object.keys(statusCodes);
          for (var statusCode = 0, totalCodes = statusKeys.length; statusCode < totalCodes; statusCode++)
          try
          if (message.indexOf(statusKeys[statusCode]) > -1)
          if (!statusCodes[statusKeys[statusCode]])
          message = message.split(statusKeys[statusCode] + ', ')[1];
          var messageParts = message.split(': ');
          if (messageParts.length > 1)
          messageParts.pop();

          message = messageParts.join(': ');
          else
          message = statusCodes[statusKeys[statusCode]];

          break;

          catch (statusCodeException)
          break;


          errorMessages.push(message);
          );

          if (errorMessages.length > 0)
          h.warning(errorMessages.join(', '), mode: 'sticky' );

          else
          h.warning('Something went wrong.', mode: 'sticky', title: 'Contact System Administrator!' );




          And on the Apex side, we can use try...catch() to handle the exceptions and the JS part will handle all the errors 0/1/N.



          try
          Integer anError = 1/0;
          catch(Exception e)
          throw new AuraHandledException(e);







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 4 at 19:01









          Robs

          2,511642




          2,511642










          answered Apr 4 at 16:21









          itzmukeshy7itzmukeshy7

          2,5191123




          2,5191123





















              1














              A purely Apex solution would be to have a AuraHandledExceptionFactory which creates the AuraHandledException with a correctly formatted error message based on the Exception type it was caught.



              Apex Controller



              Simple one line usage



              public with sharing class ApexController 

              @AuraEnabled
              public static String getAction()

              try
              // do something
              catch (Exception cause)
              throw AuraHandledExceptionFactory.create(cause);





              AuraHandledExceptionFactory



              Factory pattern used to generate the aproprate ExceptionHandler based on the type of Exception that has been provided.



              public class AuraHandledExceptionFactory 

              public static AuraHandledException create(Exception cause)
              Type handlerType = getType(cause);
              ExceptionHandler handler = newInstance(handlerType);
              return new AuraHandledException(handler.getMessage(cause));


              private static ExceptionHandler newInstance(Type handlerType)
              try
              return (ExceptionHandler) handlerType.newInstance();
              catch (Exception ignore)
              return new ExceptionHandler();



              private static Type getType(Exception cause)
              return Type.forName(getTypeName(cause));


              private static String getTypeName(Exception cause)
              return cause.getTypeName() + 'Handler';




              ExceptionHandler



              This virtual class can extended for different Exception types



              public virtual class ExceptionHandler 
              public virtual String getMessage(Exception cause)
              return cause.getMessage();




              DmlExceptionHandler



              A custom implementation to handle the DmlException type.



              public class DmlExceptionHandler extends ExceptionHandler 

              public override String getMessage(Exception cause)

              DmlException dml = (DmlException) cause;

              String message = '';

              for(integer index = 0; index < dml.getNumDML(); index++)
              // simple implementation
              message += dml.getDmlMessage(index);

              return message;




              This approach follows the Single Responsibility Principle and the Open-Closed Principle by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.



              Single Responsibility Principle




              The single responsibility principle is that states that every class
              should have responsibility over a single part of the functionality
              provided by the software, and that responsibility should be entirely
              encapsulated by the class.




              Open-Closed Principle




              The open-closed principle states classes should be open for extension,
              but closed for modification; that is, such an entity can allow its
              behaviour to be extended without modifying its source code.







              share|improve this answer





























                1














                A purely Apex solution would be to have a AuraHandledExceptionFactory which creates the AuraHandledException with a correctly formatted error message based on the Exception type it was caught.



                Apex Controller



                Simple one line usage



                public with sharing class ApexController 

                @AuraEnabled
                public static String getAction()

                try
                // do something
                catch (Exception cause)
                throw AuraHandledExceptionFactory.create(cause);





                AuraHandledExceptionFactory



                Factory pattern used to generate the aproprate ExceptionHandler based on the type of Exception that has been provided.



                public class AuraHandledExceptionFactory 

                public static AuraHandledException create(Exception cause)
                Type handlerType = getType(cause);
                ExceptionHandler handler = newInstance(handlerType);
                return new AuraHandledException(handler.getMessage(cause));


                private static ExceptionHandler newInstance(Type handlerType)
                try
                return (ExceptionHandler) handlerType.newInstance();
                catch (Exception ignore)
                return new ExceptionHandler();



                private static Type getType(Exception cause)
                return Type.forName(getTypeName(cause));


                private static String getTypeName(Exception cause)
                return cause.getTypeName() + 'Handler';




                ExceptionHandler



                This virtual class can extended for different Exception types



                public virtual class ExceptionHandler 
                public virtual String getMessage(Exception cause)
                return cause.getMessage();




                DmlExceptionHandler



                A custom implementation to handle the DmlException type.



                public class DmlExceptionHandler extends ExceptionHandler 

                public override String getMessage(Exception cause)

                DmlException dml = (DmlException) cause;

                String message = '';

                for(integer index = 0; index < dml.getNumDML(); index++)
                // simple implementation
                message += dml.getDmlMessage(index);

                return message;




                This approach follows the Single Responsibility Principle and the Open-Closed Principle by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.



                Single Responsibility Principle




                The single responsibility principle is that states that every class
                should have responsibility over a single part of the functionality
                provided by the software, and that responsibility should be entirely
                encapsulated by the class.




                Open-Closed Principle




                The open-closed principle states classes should be open for extension,
                but closed for modification; that is, such an entity can allow its
                behaviour to be extended without modifying its source code.







                share|improve this answer



























                  1












                  1








                  1







                  A purely Apex solution would be to have a AuraHandledExceptionFactory which creates the AuraHandledException with a correctly formatted error message based on the Exception type it was caught.



                  Apex Controller



                  Simple one line usage



                  public with sharing class ApexController 

                  @AuraEnabled
                  public static String getAction()

                  try
                  // do something
                  catch (Exception cause)
                  throw AuraHandledExceptionFactory.create(cause);





                  AuraHandledExceptionFactory



                  Factory pattern used to generate the aproprate ExceptionHandler based on the type of Exception that has been provided.



                  public class AuraHandledExceptionFactory 

                  public static AuraHandledException create(Exception cause)
                  Type handlerType = getType(cause);
                  ExceptionHandler handler = newInstance(handlerType);
                  return new AuraHandledException(handler.getMessage(cause));


                  private static ExceptionHandler newInstance(Type handlerType)
                  try
                  return (ExceptionHandler) handlerType.newInstance();
                  catch (Exception ignore)
                  return new ExceptionHandler();



                  private static Type getType(Exception cause)
                  return Type.forName(getTypeName(cause));


                  private static String getTypeName(Exception cause)
                  return cause.getTypeName() + 'Handler';




                  ExceptionHandler



                  This virtual class can extended for different Exception types



                  public virtual class ExceptionHandler 
                  public virtual String getMessage(Exception cause)
                  return cause.getMessage();




                  DmlExceptionHandler



                  A custom implementation to handle the DmlException type.



                  public class DmlExceptionHandler extends ExceptionHandler 

                  public override String getMessage(Exception cause)

                  DmlException dml = (DmlException) cause;

                  String message = '';

                  for(integer index = 0; index < dml.getNumDML(); index++)
                  // simple implementation
                  message += dml.getDmlMessage(index);

                  return message;




                  This approach follows the Single Responsibility Principle and the Open-Closed Principle by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.



                  Single Responsibility Principle




                  The single responsibility principle is that states that every class
                  should have responsibility over a single part of the functionality
                  provided by the software, and that responsibility should be entirely
                  encapsulated by the class.




                  Open-Closed Principle




                  The open-closed principle states classes should be open for extension,
                  but closed for modification; that is, such an entity can allow its
                  behaviour to be extended without modifying its source code.







                  share|improve this answer















                  A purely Apex solution would be to have a AuraHandledExceptionFactory which creates the AuraHandledException with a correctly formatted error message based on the Exception type it was caught.



                  Apex Controller



                  Simple one line usage



                  public with sharing class ApexController 

                  @AuraEnabled
                  public static String getAction()

                  try
                  // do something
                  catch (Exception cause)
                  throw AuraHandledExceptionFactory.create(cause);





                  AuraHandledExceptionFactory



                  Factory pattern used to generate the aproprate ExceptionHandler based on the type of Exception that has been provided.



                  public class AuraHandledExceptionFactory 

                  public static AuraHandledException create(Exception cause)
                  Type handlerType = getType(cause);
                  ExceptionHandler handler = newInstance(handlerType);
                  return new AuraHandledException(handler.getMessage(cause));


                  private static ExceptionHandler newInstance(Type handlerType)
                  try
                  return (ExceptionHandler) handlerType.newInstance();
                  catch (Exception ignore)
                  return new ExceptionHandler();



                  private static Type getType(Exception cause)
                  return Type.forName(getTypeName(cause));


                  private static String getTypeName(Exception cause)
                  return cause.getTypeName() + 'Handler';




                  ExceptionHandler



                  This virtual class can extended for different Exception types



                  public virtual class ExceptionHandler 
                  public virtual String getMessage(Exception cause)
                  return cause.getMessage();




                  DmlExceptionHandler



                  A custom implementation to handle the DmlException type.



                  public class DmlExceptionHandler extends ExceptionHandler 

                  public override String getMessage(Exception cause)

                  DmlException dml = (DmlException) cause;

                  String message = '';

                  for(integer index = 0; index < dml.getNumDML(); index++)
                  // simple implementation
                  message += dml.getDmlMessage(index);

                  return message;




                  This approach follows the Single Responsibility Principle and the Open-Closed Principle by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.



                  Single Responsibility Principle




                  The single responsibility principle is that states that every class
                  should have responsibility over a single part of the functionality
                  provided by the software, and that responsibility should be entirely
                  encapsulated by the class.




                  Open-Closed Principle




                  The open-closed principle states classes should be open for extension,
                  but closed for modification; that is, such an entity can allow its
                  behaviour to be extended without modifying its source code.








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 5 at 9:06

























                  answered Apr 4 at 20:14









                  RobsRobs

                  2,511642




                  2,511642



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Salesforce Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f256531%2fhow-to-aura-handle-multiple-dmlexceptions%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                      Luettelo Yhdysvaltain laivaston lentotukialuksista Lähteet | Navigointivalikko

                      Gary (muusikko) Sisällysluettelo Historia | Rockin' High | Lähteet | Aiheesta muualla | NavigointivalikkoInfobox OKTuomas "Gary" Keskinen Ancaran kitaristiksiProjekti Rockin' High