I have a similar question to these two: Custom Logging and Future Methods Custom Exception Handling & Logging
But my question this time is: can I put the @Future annotation on the Logger Class? Why would this not allow me to process DML even if an exception is thrown?
Scenario: I have a custom Logger class that inserts a custom record with a error message. The logger class is called at the end of every catch statement. The only way for the Logger class to insert a new record is if we do not re-throw the caught exception. I do not want to do this because if there is an exception, this indicates something is broken which should halt the entire process. This leading me to never be able to insert a new Log error record.
My thought is: if the logger method runs in the future, is it possible for the process to run, all exceptions are thrown, the process is halted, AND THEN my log message DML happens outside of the transaction?
For example:
global with sharing class NFLogger {
private enum LogLevel {Error, Info}
@Future
public static void logError(String tags, String errorMessage){
logMessage(logLevel.Error, tags, errorMessage, null);
}
@Future
public static void logError(String tags, String errorMessage, String ex){
logMessage(logLevel.Error, tags, errorMessage, ex);
}
@Future
public static void logInfo(String tags, String infoMessage){
logMessage(logLevel.Info, tags, infoMessage, null);
}
private static void logMessage(LogLevel level, String tags, String message, String ex){
try {
system.debug('Level = ' + level + ', tags = ' + tags + ', message = ' + message + ', system exception = ' + ex);
LogMessage__c newMessage = new LogMessage__c(level__c = level.name(), tags__c = tags, message__c = message, exception__c = ex);
insert newMessage;
}
catch (Exception e){
//intentionally "we suppress" any exception
//we need to guarantee that logMessage will never throw any exceptions
system.debug('in the catch of NFLogger');
}
}
}
APEX:
...
try{
TokenGenerator tg = new TokenGenerator();
String tokenizedPayload = tg.getTokenizedPayloadForSingleLead(pLead, nfId); //WEBSERVICE
return new pageReference('/apex/DLPEmailLinkUpdateSvc?id='+pLead+'&tokencred='+tokenizedPayload+'&data='+data+'&ptype=lead');
} catch (Exception ex) {
Apexpages.addMessages(ex);
NFLogger.logError('SendDLPRequestLead, tokenizer', 'There has been an error in the SendDLPRequestLead on Lead: ' + pLead, ex);
throw ex;
}