当两个.NET异常共享相同类型时,如何区分它们?

时间:2012-01-01 18:42:58

标签: .net exception exception-handling

当我遇到:

  View Certificate: .\SecurityTool.exe

System.Security.Cryptography.CryptographicException: Cannot find the requested object.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyS
torageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName)
   at CORSIS.PortFusion.Security.Tool.view@167-1.Invoke(String file) in C:\CORSIS\Software\PortFusion\0.9.3\PortFusionSource\PortFusion\SecurityTool\P
rogram.fs:line 170

   >  Private Key Password
   =  ""
   =  PS C:\CORSIS\Software\PortFusion\0.9.3\PortFusionSource\PortFusion\SecurityTool\bin\Debug> .\SecurityTool certificates view .\go.pfx
CORSIS PortFusion : Distributed Reverse Proxy Security Tool 0.9.8.0



  View Certificate: .\go.pfx

System.Security.Cryptography.CryptographicException: The specified network password is not correct.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySe
t, SafeCertContextHandle& pCertCtx)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyS
torageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName)
   at CORSIS.PortFusion.Security.Tool.view@167-1.Invoke(String file) in C:\CORSIS\Software\PortFusion\0.9.3\PortFusionSource\PortFusion\SecurityTool\P
rogram.fs:line 170

   >  Private Key Password
   =  ""
   =  PS C:\CORSIS\Software\PortFusion\0.9.3\PortFusionSource\PortFusion\SecurityTool\bin\Debug>

如何区分System.Security.Cryptography.CryptographicException的两个实例?

注意:异常文本已本地化,因此我无法对其进行匹配,因为德语,中文机器等的描述会有所不同。

3 个答案:

答案 0 :(得分:3)

您可以避免以编程方式使用消息字符串来区分异常。区分使用相同类型的异常的最佳方法如下:

  • Data字典;这并没有经常使用,但您可以检查类型之间是否存在任何不同的数据值。
  • InnerException类型(如果有)。

HResult值很有用,但无法访问(它是protected属性 - 您需要反射来读取它)。对于相同的异常类型,它也往往是相同的值。

我应该指出,如果两个异常具有相同的运行时类型,通常应该以相同的方式处理它们。评估您确实是否需要以不同方式处理它们。

答案 1 :(得分:2)

我没有测试它,但Exception.HResult属性看起来很有希望:MSDN

答案 2 :(得分:0)

他们的Message属性会有所不同。