It was to my understanding that when you throw an exception all previous operations are rolled back.
When an exception occurs, code execution halts and any DML operations that were processed prior to the exception are rolled back and aren’t committed to the database. Exceptions get logged in debug logs.
I am running into a situation where I am able to insert a record in a logger class in the catch
and throw an exception after it. What gives?
The flow is: Class A calls Class B -> Class B calls Class C -> Class C has a webservice and a try/catch
public HttpResponse postTokenizer(String securityToken, String payloadJSON) {
try {
if (payloadJSON == null) {
throw new GenericException('Tokenizer was called with no IDs. The ID must be either a Contact or Lead.');
}
HttpRequest tokenizerRequest = new HttpRequest();
tokenizerRequest.setMethod('POST');
tokenizerRequest.setEndpoint(tokensAPIEndpoint);
tokenizerRequest.setHeader('Authorization', 'token ' + securityToken);
tokenizerRequest.setHeader('Content-Type', 'application/json');
tokenizerRequest.setTimeout(30000);
tokenizerRequest.setBody(payloadJSON);
Http http = new Http();
HttpResponse response = http.send(tokenizerRequest);
if (!WebHelper.isSuccessStatus(response)) {
throw new GenericException('There has been an error calling the tokenizer service.');
}
return response;
} catch(Exception e) {
NFLogger.logError('TokenizerHelper, tokenizer', 'Call to postTokenizer() failed.', e); //todo:: how is this inserting????? shouldn't this be rolled back?
throw e;
}
}
NFLOGGER:
global with sharing class NFLogger {
private enum LogLevel {Error, Info}
public static void logError(String tags, String errorMessage){
logMessage(logLevel.Error, tags, errorMessage, null);
}
public static void logError(String tags, String errorMessage, System.Exception ex){
logMessage(logLevel.Error, tags, errorMessage, ex);
}
public static void logInfo(String tags, String infoMessage){
logMessage(logLevel.Info, tags, infoMessage, null);
}
private static void logMessage(LogLevel level, String tags, String message, System.Exception ex){
try {
LogMessage__c newMessage = new LogMessage__c(level__c = level.name(), tags__c = tags, message__c = message, exception__c = ex.getMessage());
insert newMessage;
}
catch (Exception e){
//intentionally we are ignoring "we suppress" any exception
//we need to guarantee that logMessage will never throw any exceptions
}
}
}
Platform Events
? – Adrian Larson♦ Nov 12 '18 at 20:15NFLogger
work? It could be using platform events to get outside of the transaction to avoid the rollback. Or if a higher class in the callstack is catching the exception the transaction won't be rolled back. – Daniel Ballinger Nov 12 '18 at 20:15