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) {
ExceptionHandler handler = newInstance(getType(cause));
return new AuraHandledException(handler.getMessage(cause));
}
private static ExceptionHandler newInstance(Type handlerType) {
ExceptionHandler handler;
try {
handler = (ExceptionHandler) handlerType.newInstance();
} catch (Exception catastrophe) {
handler = new ExceptionHandler();
}
return handler;
}
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 Pattern
and the Open-Closed Pattern
by keeping each class clean and simple, while still enabling you to extend it to handle your own custom exception types.
Single Responsibility Pattern
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 Pattern
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.