如果有任何错误(任何人)捕获此错误并写入日志,该怎么做?
最近客户更改了密码网站管理员(用于验证发送邮件的电子邮件) 这意味着系统不再能够发送电子邮件。 问题是几天后才发现错误。
您想要一种方法来捕获此错误并保存邮件(电子邮件)和日志错误,如何?
在控制器中
new MailController(_subsidiaryService).PedidoOrcamentoEmail(model).DeliverAsync();
MailController中的
public EmailResult PedidoOrcamentoEmail(BudgetViewModel model)
{
From = string.Format("{0} <{1}>", model.Name, model.Email);
To.Add("Site <" + ConfigurationManager.AppSettings["toEmail"] + ">");
var subInfo = (from s in _subsidiaryService.Repository.Query()
where s.ID == model.SubsidiaryID
select new
{
s.Title,
s.District
}).SingleOrDefault();
ViewData["SubsidiaryTitle"] = subInfo.Title;
ViewData["SubsidiaryDistrict"] = subInfo.District;
Subject = "[Pedido de Orçamento] " + model.Name;
return Email("PedidoOrcamentoEmail", model);
}
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
// This is not executed
base.OnException(filterContext);
}
作为测试,我输入了无效的密码电子邮件网站管理员(用于发货)
答案 0 :(得分:1)
创建一个自定义MailSender,它继承自默认的MailSender,并将调用包装在try..catch块中的基本方法中。然后,当发生异常时,您可以执行任何操作。
public class CustomMailSender : SmtpMailSender
{
private readonly ILog _log = LogManager.GetCurrentClassLogger();
public CustomMailSender() { }
public CustomMailSender(SmtpClient client) : base(client) { }
public new void Send(MailMessage mail)
{
try
{
base.Send(mail);
//Do some logging if you like
_log.Info(....)
}
catch (SmtpException e)
{
//Do some logging
var message = mail.RawMessageString();
_log.Error(message, e);
// rethrow if you want...
}
}
public new void SendAsync(MailMessage mail, Action<MailMessage> callback)
{
... similar ...
}
}
在MailController中,CustomMailSender的使用方式如下:
public MailController() {
MailSender = new MyCustomMailSender();
}