在Apex中发生异常时,把异常信息以邮件形式发生出去。
SendEmailUtils.cls
代码语言:javascript复制public with sharing class SendEmailUtils {
public static void sendMailFromEx() {
try {
List<Opportunity> oppList = new List<Opportunity>();
Opportunity oppItem1 = new Opportunity();
oppItem1.Name = 'test001';
oppItem1.StageName = 'Prospecting';
//oppItem1.CloseDate = System.today();
oppList.add(oppItem1);
insert oppList;
} catch (Exception ex) {
List<OrgWideEmailAddress> owea = [select id from OrgWideEmailAddress limit 1];
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { 'xxxx1987@163.com' });
email.setSubject('my subject');
// メール送信内容作成
String body = String.format('my subject', new String[]{Datetime.now().format('yyyy-MM-dd kk:mm:ss.S', 'Asia/Tykyo'),
String.ValueOf(ex.getMessage()),
String.ValueOf(UserInfo.getUserName()),
String.ValueOf(UserInfo.getSessionId()),
String.ValueOf(ex.getStackTraceString())
});
email.setPlainTextBody(body);
If (owea != null && owea.size() > 0) {
email.setOrgWideEmailAddressId(owea.get(0).id);
} else {
email.setSenderDisplayName('Salesforce Support');
}
List<Messaging.SendEmailResult> results =
Messaging.sendEmail(new Messaging.Email[] { email });
if (!results.get(0).isSuccess()) {
System.StatusCode statusCode = results.get(0).getErrors()[0].getStatusCode();
String errorMessage = results.get(0).getErrors()[0].getMessage();
system.debug(errorMessage);
} else {
system.debug('The email was sent successfully.');
}
throw ex;
}
}
}
为了测试,在开发者Console中调用当前Apex
看上边log,虽然显示发送成功,但是并没有收到邮件,看来在异常处理里边无法发送出去,只能另外想办法。
使用Platform Event方式实现
Platform Event是基于发布订阅模式,当salesforce发布消息以后,他的订阅者都有权力去订阅到发布的数据,当前场景下当异常发生时,发布消息,在通过trigger发送邮件信息。
自定义项目做成,用于保存error信息。
代码语言:javascript复制public with sharing class SendEmailUtils {
public static void sendMailFromEx() {
try {
List<Opportunity> oppList = new List<Opportunity>();
Opportunity oppItem1 = new Opportunity();
oppItem1.Name = 'test001';
oppItem1.StageName = 'Prospecting';
//oppItem1.CloseDate = System.today();
oppList.add(oppItem1);
insert oppList;
} catch (Exception ex) {
List<SendEmail__e> needPublishSendEmailList = new List<SendEmail__e>();
SendEmail__e sendEmailPublishItem = new SendEmail__e();
sendEmailPublishItem.Exception_Content__c = String.ValueOf(ex.getMessage());
sendEmailPublishItem.StackTrace__c = String.ValueOf(ex.getStackTraceString());
needPublishSendEmailList.add(sendEmailPublishItem);
if(!needPublishSendEmailList.isEmpty()) {
List<Database.SaveResult> results = EventBus.publish(needPublishSendEmailList);
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
System.debug('Successfully published event.');
} else {
for(Database.Error err : sr.getErrors()) {
System.debug('Error returned: ' err.getStatusCode() ' - ' err.getMessage());
}
}
}
}
throw ex;
}
}
}
代码语言:javascript复制trigger SendEmailTrigger on SendEmail__e (after insert) {
for(SendEmail__e sendEmailItem : (List<SendEmail__e>)Trigger.new) {
List<OrgWideEmailAddress> owea = [select id from OrgWideEmailAddress limit 1];
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { 'xxxxxx1987@163.com' });
email.setSubject('my subject');
// メール送信内容作成
String body = String.format('my subject',
new String[]{Datetime.now().format('yyyy-MM-dd kk:mm:ss.S', 'Asia/Tykyo'),
sendEmailItem.Exception_Content__c,
String.ValueOf(UserInfo.getUserName()),
String.ValueOf(UserInfo.getSessionId()),
sendEmailItem.StackTrace__c
});
email.setPlainTextBody(body);
If (owea != null && owea.size() > 0) {
email.setOrgWideEmailAddressId(owea.get(0).id);
} else {
email.setSenderDisplayName('Salesforce Support');
}
List<Messaging.SendEmailResult> results =
Messaging.sendEmail(new Messaging.Email[] { email });
if (!results.get(0).isSuccess()) {
System.StatusCode statusCode = results.get(0).getErrors()[0].getStatusCode();
String errorMessage = results.get(0).getErrors()[0].getMessage();
system.debug(errorMessage);
} else {
system.debug('The email was sent successfully.');
}
}
}