To set up for this class add two Boolean fields to your User object.
Apex_Error_Email__c - set true to indicate this user should receive emails on error. Apex_Info_Email__c - set true to indicate this user should receive emails on significant events.
public with sharing class ErrorUtilities { /* Send email with ERROR message to Users that have custom property Apex_Error_Email__c == true * Input: * String callerName, text to identify which piece of code called the method. * String errorMessage, the main error message to send */ public static void reportError(String callerName, String errorMessage) { User[] contacts = [select Id, Name, Email from User where Apex_Error_Email__c = true AND IsActive = true]; report(callerName, contacts,'Error message: ',errorMessage); } /* Send email with INFORMATION message to Users that have custom property Apex_Info_Email__c == true * Input: * String callerName, text to identify which piece of code called the method. * String infoMessage, the main information message to send */ public static void reportInfo(String callerName, String infoMessage) { User[] contacts = [select Id, Name, Email from User where Apex_Info_Email__c = true AND IsActive = true]; report(callerName, contacts,'Information message: ',infoMessage); } /* Compose an error message using the optional Exception and optional reference ID to a Salesforce Object * */ public static void handleError(System.Exception e, String refId, String callerName, String errorMessage){ String msg = errorMessage + '\n'; if(refId != null) { String baseURL = URL.getSalesforceBaseUrl().toExternalForm() + '/'; String refURL = baseURL + refId; msg += '\n\n'; msg += 'See: ' + refURL +'\n'; } if(e != null) { msg += '\n'; msg += 'EXCEPTION:\n Error: ' + e.getMessage() + '\n'; msg += ' Type: ' + e.getTypeName() + '\n'; msg += ' Line Number: ' + e.getLineNumber() + '\n'; msg += ' Trace:\n' + e.getStackTraceString() + '\n(end stack trace)\n'; } ErrorUtilities.reportError(callerName, msg); } private static void report(String callerName, User[] contacts, String subjectPrefix,String errorMessage) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] sendTo = new String[]{}; for(User aUser : contacts) { sendTo.add(aUser.Email); } mail.setToAddresses(sendTo); mail.setSubject(subjectPrefix + callerName); mail.setPlainTextBody('Message: \n' + errorMessage); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } public static testmethod void testReportError() { ErrorUtilities.reportError('ErrorUtilities.testReportError', 'This is just a test.'); ErrorUtilities.reportInfo('ErrorUtilities.testReportError', 'This is just a test.'); Account sampleAccount = [select Id from Account limit 1]; ErrorUtilities.handleError(null,sampleAccount.Id,'ErrorUtilities.testReportError','unit testing handle error'); } }
No comments:
Post a Comment