전자 메일을 보내는 단일 메서드로 간단한 클래스를 코딩하고 있습니다. 필자의 목표는 레거시 Visual Basic 6 프로젝트에서이를 구현하여 COM Interop 기능을 통해 COM 개체로 노출시키는 것입니다.예외 처리 : 인수 유효성 검사와 관련하여 얼마나 세분합니까?
세부 사항이 있습니다. 해결하기 어려운 부분이 있습니다. 매개 변수의 유효성을 검사하는 방법이 세분화되어야합니다. 그래서, 어떤 제안이 많이 이해할 수있을 것이다
public class MyMailerClass
{
#region Creation
public void SendMail(string from, string subject, string to, string body)
{
if (this.IsValidMessage(from, subject, to, body)) // CS1501
{
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress(from);
msg.To.Add(to);
msg.Subject = subject;
msg.Body = body;
SmtpClient srv = new SmtpClient("SOME-SMTP-HOST.COM");
srv.Send(msg);
}
else
{
throw new ApplicationException("Invalid message format.");
}
}
#endregion Creation
#region Validation
private bool IsValidMessage(string from, string subject, string to, string body)
{
Regex chk = new Regex(@"(\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,6})");
if (!chk.IsMatch(from))
{
return false;
}
if (!chk.IsMatch(to))
{
return false;
}
if (!string.IsNullOrEmpty(subject))
{
return false;
}
if (!string.IsNullOrEmpty(body))
{
return false;
}
else
{
return true;
}
}
#endregion Validation
}
: 그 빛에, 난 정말에 대한 행복하지 않다, 그리고 일이 전혀 실제로 예외를 처리하고있어 방법 세부되어 아니다 귀하의 의견은 모두에 미리 감사드립니다.
참고 :이 특별한 경우에 엔터프라이즈 라이브러리 Validation Application Block을 구현하는 것이 편리할까요?
당신을 ArgumentException을 잘못 사용하고 있습니다 - 두 번째 인수는 유효하지 않은 인수의 _name_이어야하는 _string_입니다. 대신, 당신은 그 논쟁의 가치를 거기에 전달하고 있습니다. 당신은 다음과 같이해야합니다 :'new ArgumentException ("잘못된 발신자 주소 :"+ from ","from "); –
감사합니다. Pavel, 고맙습니다. –
새로운 버전의 코드는 디버그하기가 어렵습니다. IsValidMessage()에서는 모든 조건을 한 줄로 확인합니다. 디버거를 사용하여 코드를 단계별로 실행할 때 만족되지 않는 것을 어떻게 찾을 수 있습니까? 다음과 같이 작성할 수 있습니다 : if (string.IsNullOrEmpty (subject)) {return false; } if (! string.IsNullOrEmpty (body)) {return false; } 그런 다음 Regex 객체를 만들고 조건을 한 번만 확인하면 조건이 만족되지 않으면 즉시 false가 반환됩니다. – sharptooth