我正在写信寻求有关为test
方法实现return语句的帮助。我目前从我的test()方法得到一个null响应,但我想知道,如何在我的"IsValidEmailDomain"
方法中从"test"
方法中捕获错误:
public static bool IsValidEmailDomain(MailAddress address)
{
if (address == null) return false;
var response = DnsClient.Default.Resolve(address.Host, RecordType.Mx);
try
{
if (response == null || response.AnswerRecords == null) return false;
}
catch (FormatException ex)
{
ex.ToString();
throw ex;
//return false;
}
return response.AnswerRecords.OfType<MxRecord>().Any();
}
public static bool IsValidEmailDomain(string address)
{
if (string.IsNullOrWhiteSpace(address)) return false;
MailAddress theAddress;
try
{
theAddress = new MailAddress(address);
}
catch (FormatException)
{
return false;
}
return IsValidEmailDomain(theAddress);
}
public static string test()
{
string mail = "########";
if (IsValidEmailDomain(mail))
{
return mail;
}
else
{
///How to return error from IsValidEmailDomain() method.
}
}
任何提示或建议都将非常受欢迎。
答案 0 :(得分:1)
public static string test()
{
string mail = "########";
bool? answer;
Exception ex;
try
{
answer = IsValidEmailDomain(mail);
}
catch(Exception e)
{
ex = e;
}
if (answer)
{
return mail;
}
else
{
// here you can check to see if the answer is null or if you actually got an exception
}
}
答案 1 :(得分:0)
有几种方法可以做到这一点。
out
参数。当我遇到这样的事情时,我通常会选择组合。
public bool IsValidEmailDomain(string email)
{
return IsValidEmailDomain(email, false);
}
public bool IsValidEmailDomain(string email, bool throwErrorIfInvalid)
{
string invalidMessage;
var valid = ValidateEmailDomain(email, out invalidMessage);
if(valid)
return true;
if (throwErrorIfInvalid)
throw new Exception(invalidMessage);
return false;
}
public bool ValidateEmailDomain(string email, out string invalidMessage)
{
invalidMessage= null;
if (....) // Whatever your logic is.
return true;
invalidMessage= "Invalid due to ....";
return false;
}