【发布时间】:2019-08-21 09:04:39
【问题描述】:
在下面的代码中,我尝试发送一组通知,我想知道通知是否发送成功(稍后将其放入数据库中,因此不再发送)。
我在这里抓到Exception 是不是很糟糕?我真的不在乎未发送通知的原因。
private static async Task<List<Tuple<NotificationToSend, bool>>> SendNotificationsAsync(IEnumerable<NotificationToSend> notificationsToSend)
{
var tuples = new List<Tuple<NotificationToSend, bool>>();
using (var smtpClient = new SmtpClient())
{
foreach (var notification in notificationsToSend)
{
bool sentSuccessfully;
try
{
var mailMessage = new MailMessage
{
Subject = notification.Subject,
Body = $"{notification.Text} <br /> This notification was sent automatically",
IsBodyHtml = true
};
mailMessage.To.Add(notification.ToEmail);
await smtpClient.SendMailAsync(mailMessage);
sentSuccessfully = true;
}
catch (Exception e)
{
sentSuccessfully = false;
// Here I also plan to log the exception
}
var tuple = new Tuple<NotificationToSend, bool>(notification, sentSuccessfully);
tuples.Add(tuple);
}
}
return tuples;
}
【问题讨论】:
-
“这真的很糟糕吗”非常基于意见,不是吗?不可能在这里发布“正确”或“错误”的答案。
-
你的
try块可以更小,但你只需要await smtpClient.SendMailAsync(mailMessage);和sentSuccessfully = true; -
@ZoharPeled 如果
notification为空怎么办? -
你真的想抓住
NullReferenceException吗? -
@ZoharPeled 不是。我不想抓住任何东西。我只是想看看通知是否发送成功。
标签: c# .net exception .net-4.0