如何从bool类型方法中捕获错误

本文关键字:错误 方法 类型 bool | 更新日期: 2023-09-27 18:25:19

我写这篇文章是为了寻求有关为test方法实现返回语句的帮助。我目前从我的test()方法得到了一个null响应,但我想知道,如何在我的"test"方法中捕获来自"IsValidEmailDomain"方法的错误:

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.
    }
}

任何提示或建议都将不胜感激。

如何从bool类型方法中捕获错误

  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
            }
        }

有几种方法可以做到这一点。

  • 使用out参数
  • 如果出现问题,则抛出异常。(违背了bool的目的)

当我遇到这样的东西时,我通常会选择组合。

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;
}