Skip to content

Instantly share code, notes, and snippets.

@justin-lyon
Last active March 11, 2020 12:36
Show Gist options
  • Save justin-lyon/a9fc8f3045cdaa5e73659c87430ddcb6 to your computer and use it in GitHub Desktop.
Save justin-lyon/a9fc8f3045cdaa5e73659c87430ddcb6 to your computer and use it in GitHub Desktop.
Custom Apex error logging sample.

Custom Apex Error Logger

Implement a custom error logging framework from scratch.

Assumes a Custom Object ErrorLog exists.

public virtual class LoggableException extends Exception {
private ErrorLog__c errorLog;
private List<ExceptionLog__c> exceptionLogs;
private List<RowLog__c> rowLogs;
private List<ServiceLog__c> serviceLogs;
public void init(Exception exc) {
errorLog = new ErrorLog__c();
exceptionLogs = new List<ExceptionLog__c>();
rowLogs = new List<RowLog__c>();
serviceLogs = new List<ServiceLog__c>();
// initialize logger with the first exception
}
public void addException(Exception exc) {
// add an exception to the error log
}
public void flush() {
// commit all data to salesforce
}
}
public class MyBusinessLayer {
MyDataLayer data = new MyDataLayer();
public void doThing () {
Contact newContact = newContact(Id = '00300000000000a');
try {
data.insertContact(newContact);
} catch(LoggableException lexc) {
MyCustomException myexc = new MyCustomException(lexc);
lexc.addException(myexc);
throw myexc;
}
}
}
public class MyDataLayer {
public void insertContact (Contact newContact) {
try {
insert newContact;
} catch (DmlException dmle) {
// Catch and Handle a DML Exception
// Record it to an SObject and attach it to my custom exception
LoggableException loggable = exc.init(dmle);
// Rethrow the exception so the Application and/or Presentation Layers can handle it.
// Upper layers in the stack may get and add more context to the Error Log
// as the exception bubbles up the stack.
throw loggable;
}
}
}
public class MyException extends LoggableException {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment