如何获取 InnerException 的详细信息

Jua*_*eza 2 c# exception

关于重复。我可以访问该Message属性,但不能访问该属性,Detail即使在调试期间我可以看到它是 Exception 对象的一部分。所以问题是为什么不能访问Detail财产。

我捕捉到一个异常。

catch (Exception ex)
{
    string msg = ex.InnerException.InnerException.Message;
    // say Exception doesnt have Detail property
    // string detail = ex.InnerException.InnerException.Detail; 
    return Json(new { status = "Fail", message = msg, detail: detail });
}
Run Code Online (Sandbox Code Playgroud)

前任什么都不说 在此处输入图片说明

ex.InnerException显示相同的消息 在此处输入图片说明

例如.InnerException.InnerException。终于有一些真实的消息,"db table duplicated key" 在此处输入图片说明

ex.InnerException.InnerException.Message我可以得到消息。 在此处输入图片说明

但是"the guilty key"即使有一个属性也无法获得详细信息Detail

在此处输入图片说明

  1. 那么我怎样才能得到细节呢?
  2. 奖励:为什么要深入InnerException两次才能获得一些有意义的信息?

chi*_*s0v 5

我认为现在最优雅的方法是在 catch 语句中使用C# 6 关键字,C# 7 是 operator

try
{
    //your code
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException pex)
{
    string msg = pex.Message;
    string detail = pex.Detail; 
    return Json(new { status = "Fail", message = msg, detail: detail });
}
Run Code Online (Sandbox Code Playgroud)