Skip to content

Instantly share code, notes, and snippets.

@jmather
Created August 8, 2019 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmather/8be36c901aa1242c6bd65acb8003f009 to your computer and use it in GitHub Desktop.
Save jmather/8be36c901aa1242c6bd65acb8003f009 to your computer and use it in GitHub Desktop.
Custom Apex Exceptions with stack traces!
/**
* Created by Jacob Mather <jmather@jmather.com> on 2019-06-25.
*/
global with sharing class Sentry_Exception extends Exception {
global Map<String, Object> context = new Map<String, Object>();
private List<String> stackTrace;
global void setStackTrace(List<String> lines) {
stackTrace = lines;
}
global String getCustomStackTraceAsString() {
return String.join(getCustomStackTrace(), '\n');
}
global List<String> getCustomStackTrace() {
if (stackTrace != null) {
return stackTrace;
}
return new List<String>();
}
}
/**
* Created by jmather on 2019-08-08.
*/
global with sharing class Sentry_ExceptionFactory {
global static Sentry_Exception build() {
return (Sentry_Exception) build(Sentry_Exception.class);
}
global static Exception build(String exceptionClass) {
Type exType = Type.forName(exceptionClass);
return build(exType);
}
global static Exception build(Type exType) {
try {
Sentry_Exception ex = (Sentry_Exception) exType.newInstance();
try {
SObject foo = null;
Id fooId = foo.Id;
} catch (Exception e) {
String stack = e.getStackTraceString();
List<String> lines = stack.split('\n');
lines.remove(0);
lines.remove(0);
ex.setStackTrace(lines);
return ex;
}
} catch (Exception e) {
}
try {
Exception ex = (Exception) exType.newInstance();
return ex;
} catch (Exception e) {
}
Sentry_Exception ex = (Sentry_Exception) Sentry_ExceptionFactory.build(Sentry_Exception.class);
ex.setMessage('Could not instantiate given class as an exception!');
ex.context.put('exceptionClass', exType.getName());
return ex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment