[英]How to correctly handle System.Net.Mail.SmtpException?
我有一个简单的smtpClient:
var smtp = new SmtpClient { Host = host, ...};
smtp.Send(message);
我可以拥有一个不同的主人: smtp.gmail.com
, smtp.yandex.ru
等。
当smtp.Send(message);
执行我有不同的例外(取决于主机)由于同样的问题 - 双因素验证关闭。
对于gmail,其System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
对于yahoo和yandex,其System.Net.Mail.SmtpException depth 0: The operation has timed out. (0x80131500)
System.Net.Mail.SmtpException depth 0: The operation has timed out. (0x80131500)
我现在不介绍其他邮件提供程序异常但是如何正确抛出异常(“你需要启用双因素验证”)只需一次? 可能吗? 或者如何最小化代码重复?
我不确定你是如何选择使用哪个主机( if
或switch
语句?)但你可以考虑添加两个从SmtpClient继承的新客户端类,例如YahooClient:
class YahooClient : SmtpClient {
private const string Host = "smtp.yahoo.com";
Send(MailMessage message) {
/// Call base send and handle exception
try {
base.Send(message)
}
catch(ex as SmtpException) {
// Handle accordingly
}
}
}
此外,您可以引入实现一个合适的接口,并使用IoC(或策略模式等)根据您的配置注入正确的客户端,例如
class YahooClient : SmtpClient, IMySmtpClient {
}
interface IMySmtpClient {
void Send(MailMessage message);
}
class ConsumingMailSender(IMySmtpClient client) {
// Create message and send
var message = new MailMessage etc....
client.Send(message);
}
这可能是矫枉过正,但可以避免违反SRP并且必须在您当前用于发送电子邮件的方法中执行条件逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.