簡體   English   中英

C# 與 PowerShell。 如何獲取詳細的異常信息?

[英]C# vs PowerShell. How to get detailed exception info?

我正在通過 COM 接口使用一些外部庫。 我有通用類。

Database.Connector connector = new Database.Connector();
string connectString = "srvr=nonexisthost;database=test;"; // bogus connect string
try
{
    var database = connector.Connect(connectString);
}
catch (COMException ex)
{
    Console.WriteLine(ex.Message);
}

試圖建立一個錯誤證明邏輯我故意引發異常。

而且我發現 C# COMException 只包含通用信息,例如:

調用 COM 組件時返回了錯誤 HRESULT E_FAIL。

在 PowerShell 中執行相同的代碼會得到更詳細的描述:

$connector = New-Object -ComObject Database.Connector
$connectString = "srvr=nonexisthost;database=test;"
$database = $connector.Connect($connectString)

使用信息庫 server_addr=nonexisthost descr=11001(0x00002AF9) 執行事務時出錯:主機未知。 行=1048 文件=src\\DataExchangeCommon.cpp

我的問題是:我應該怎么做才能在 C# 中獲得相同的錯誤信息(如果可能的話)?

我不是 COM Interop 專家,但我會盡力回答我所知道的,希望對您有所幫助。

從托管方

如果 HRESULT 被運行時 (CLR) 識別,則運行時會自動為該錯誤創建一個特定的托管異常(例如 FileNotFoundException)。 否則,運行時會創建一個通用的 COMException 對象,它說“我不知道這個 HRESULT 是什么意思”。

如果非托管代碼提供錯誤信息,您將在 ErrorCode 屬性中看到它,否則,您將只看到 HRESULT 代碼。 您可以嘗試搜索此代碼(google\\github)以獲取更多信息。

從非托管方面

您需要實現 ISupportErrorInfo 和 IErrorInfo 接口以提供更多信息。

因此,要回答您的問題,在 C# 中,如果未提供此信息,您將無法在 COMException 對象中獲得更多信息。

有關詳細信息: COMException處理 COM 互操作異常IErrorInfoISupportErrorInfoHRESULT 的映射通用 HRESULT 值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM