[英]How to get Exception Error Code in C#
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
}
當我調用上述 WMI 方法時,我預計會被拒絕訪問。 在我的 catch 塊中,我想確保引發的異常確實是針對拒絕訪問的。 有什么辦法可以得到它的錯誤代碼嗎? Access Denied 的 Win32 錯誤代碼是 5。我不想在錯誤消息中搜索被拒絕的字符串或類似內容。
謝謝
您可以使用它來檢查Win32Exception 派生異常的異常和內部異常。
catch (Exception e) {
var w32ex = e as Win32Exception;
if(w32ex == null) {
w32ex = e.InnerException as Win32Exception;
}
if(w32ex != null) {
int code = w32ex.ErrorCode;
// do stuff
}
// do other stuff
}
從 C# 6 開始,可以在 catch 語句中使用when來指定一個條件,該條件對於要執行的特定異常的處理程序來說必須為真。
catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
var w32ex = (Win32Exception)ex.InnerException;
var code = w32ex.ErrorCode;
}
正如在評論中一樣,您確實需要查看實際拋出的異常以了解您可以做什么,並且在這種情況下,特定的捕獲優於僅捕獲異常。 就像是:
catch (BlahBlahException ex) {
// do stuff
}
catch (Exception ex) {
var code = ex.HResult;
}
但是,它僅適用於 .NET 4.5 以上。
以 Preet Sangha 的解決方案為基礎,以下內容應該可以安全地涵蓋您正在使用可能出現多個內部異常的大型解決方案的場景。
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
if (ExceptionContainsErrorCode(e, 10004))
{
// Execute desired actions
}
}
...
private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
Win32Exception winEx = e as Win32Exception;
if (winEx != null && ErrorCode == winEx.ErrorCode)
return true;
if (e.InnerException != null)
return ExceptionContainsErrorCode(e.InnerException, ErrorCode);
return false;
}
此代碼已經過單元測試。
通過在自己的塊中管理每個預期的異常類型,我不會過多強調在異常處理方面需要了解和實施良好實踐。
您應該查看拋出異常的成員,特別是.Message
和.InnerException
。
我還將查看 InvokeMethod 的文檔是否告訴您它是否拋出一些比 Exception 更專業的 Exception 類 - 例如 @Preet 建議的 Win32Exception。 捕獲並僅查看 Exception 基類可能不是特別有用。
我建議你使用來自異常對象的消息屬性如下代碼
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
//use Console.Write(e.Message); from Console Application
//and use MessageBox.Show(e.Message); from WindowsForm and WPF Application
}
另一種方法是直接從異常類中獲取錯誤代碼。 例如:
catch (Exception ex)
{
if (ex.InnerException is ServiceResponseException)
{
ServiceResponseException srex = ex.InnerException as ServiceResponseException;
string ErrorCode = srex.ErrorCode.ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.