我试图使用枚举来汇总System.Net.Mail.SmtpClient.Send
的结果。这是我知道我是否应该重试发送电子邮件,并希望防止发送重复的电子邮件。
public enum MailSendStatus {
None,
Sent,
ErrorCannotSend,
TryAgain,
SentMaybe
}
我抓住了Send
的所有例外情况,并将SmtpException.StatusCode
与http://msdn.microsoft.com/en-us/library/system.net.mail.smtpstatuscode(v=vs.80).aspx分开。故障看起来是否合适?或者有更好的方法吗?
try {
smtp.Send(msg);
} catch (ArgumentNullException e) {
return MailSendStatus.ErrorCannotSend;
} catch (ObjectDisposedException e) {
return MailSendStatus.ErrorCannotSend;
} catch (InvalidOperationException e) {
return MailSendStatus.ErrorCannotSend;
} catch (SmtpFailedRecipientsException e) {
return MailSendStatus.ErrorCannotSend;
} catch (SmtpException e) {
switch(e.StatusCode) {
case SmtpStatusCode.BadCommandSequence:
case SmtpStatusCode.MailboxNameNotAllowed:
case SmtpStatusCode.HelpMessage:
case SmtpStatusCode.SyntaxError:
case SmtpStatusCode.SystemStatus:
return MailSendStatus.ErrorCannotSend;
case SmtpStatusCode.CannotVerifyUserWillAttemptDelivery:
case SmtpStatusCode.UserNotLocalWillForward:
return MailSendStatus.SentMaybe;
case SmtpStatusCode.ClientNotPermitted:
case SmtpStatusCode.CommandNotImplemented:
case SmtpStatusCode.CommandParameterNotImplemented:
case SmtpStatusCode.CommandUnrecognized:
case SmtpStatusCode.ExceededStorageAllocation:
case SmtpStatusCode.GeneralFailure:
case SmtpStatusCode.InsufficientStorage:
case SmtpStatusCode.LocalErrorInProcessing:
case SmtpStatusCode.MailboxBusy:
case SmtpStatusCode.MailboxUnavailable:
case SmtpStatusCode.MustIssueStartTlsFirst:
case SmtpStatusCode.ServiceClosingTransmissionChannel:
case SmtpStatusCode.ServiceNotAvailable:
case SmtpStatusCode.ServiceReady:
case SmtpStatusCode.StartMailInput:
case SmtpStatusCode.TransactionFailed:
case SmtpStatusCode.UserNotLocalTryAlternatePath:
return MailSendStatus.TryAgain;
case SmtpStatusCode.Ok:
break;
}
} catch (Exception e) {
return MailSendStatus.SentMaybe;
}
return MailSendStatus.Sent;
答案 0 :(得分:2)
catch (ArgumentNullException e) { return MailSendStatus.ErrorCannotSend;} catch
(ObjectDisposedException e) { return MailSendStatus.ErrorCannotSend;} catch
(InvalidOperationException e) { return MailSendStatus.ErrorCannotSend;
我不喜欢这个。 ArgumentNull,ObjectDisposed是编程错误(与InvalidOperation一样)。您不应该将它们分解为SMTP错误,但要修复它们。 Fpr这个,崩溃程序很好(并且发出堆栈跟踪)。方法“快速失败”。不要重新知道你不知道如何处理的异常,并且InvalidOperationException,ObjectDisposedException指示状态有问题,ArbumentNullException是一个usage / ui错误。