.NET异常和错误字段

时间:2016-02-17 20:30:34

标签: c# exception exception-handling

我使用第三方组件(SendGrid),此组件抛出异常:

        var myMessage = new SendGridMessage();
        myMessage.AddTo(element.Receiver);
        myMessage.From = new System.Net.Mail.MailAddress(element.SenderEmail, element.SenderName);
        myMessage.Subject = element.Subject;
        myMessage.Text = element.Body;
        myMessage.Html = element.Body;

        string sendGridApiKey = ConfigurationManager.AppSettings["SendGridApiKey"];
        var transportWeb = new SendGrid.Web(sendGridApiKey);
try
{
    await transportWeb.DeliverAsync(myMessage);
}
catch (Exception ex)
{
}

调试器说,“ex”包含带有错误数组的字段错误,ex.Message ='错误请求检查Errors以获取API返回的错误列表。'

但如果我试着写点什么:

var x = ex.Errors;

它说

  

严重级代码描述项目文件行抑制状态   错误CS1061'异常'不包含'错误'的定义,并且没有扩展方法'错误'接受类型'异常'的第一个参数可以找到(你是否缺少using指令或程序集引用?)SendGridEmailService

如何实现它(据我所知,未知命名空间有一个例外)如何知道这个异常?

3 个答案:

答案 0 :(得分:2)

我经过一番搜索后在网上找到了这个,看起来你想要InvalidApiRequestException

try
{
    await transportWeb.DeliverAsync(myMessage);
}
catch (InvalidApiRequestException ex)
{
}

如果您仍想尝试捕获所有异常,可以执行以下操作:

try
{
    await transportWeb.DeliverAsync(myMessage);
}
catch (Exception ex)
{
    var ex2 = ex as InvalidApiRequestException;
    if(ex2 != null)
    {
        var x = ex2.Errors;
    }
}

InvalidApiRequestException Source

发现于: http://www.rolandocr.com/2015/06/how-to-using-sendgrid-csharp-library-and-deliverasync-method-error-handling-and-async-pattern/#sthash.1mVXMDWh.dpbs

答案 1 :(得分:2)

您必须查看Exception的运行时类型并将ex强制转换为该类型,或将catch定义为此类异常类型,例如,如果类型异常ErrorsException

try
{
    await transportWeb.DeliverAsync(myMessage);
}
catch (ErrorsException ex)
{
    var errors = ex.Errors
}

classs ErrorsException : Exception
{
    public string[] Errors { get; set; }
}

答案 2 :(得分:1)

异常可能不包含错误字段,因此您将收到编译错误。 ex本身是Exception的某个子类的一个实例,但是编译器不知道哪个,它只知道它可以在你声明" Exception ex"时分配给Exception。因此,解决方案是捕获更具体的异常,这也是一种很好的做法,因为通过捕获一般异常,您将捕获所有异常,这是您通常不想要的。

如果你想在运行时获得ex的实际类型,可以使用ex.GetType(),但是你应该能够在调试器中看到它。