如何在C#中获取异常错误代码

Fra*_* Q. 19 c# exception

try
{
     object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{  
    // Here I was hoping to get an error code.
}
Run Code Online (Sandbox Code Playgroud)

当我调用上面的WMI方法时,我应该得到Access Denied.在我的catch块中,我想确保引发的异常确实是Access Denied.有没有办法可以得到它的错误代码?Acceess Denied的Win32错误代码是5.我不想在错误消息中搜索拒绝字符串或类似的东西.

谢谢

Pre*_*gha 34

尝试这个来检查异常和内部的一个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   
}
Run Code Online (Sandbox Code Playgroud)

在注释中,您确实需要查看实际抛出的异常以了解您可以执行的操作,并且在这种情况下,特定的catch优先于捕获Exception.就像是:

  catch (BlahBlahException ex){  
      // do stuff   
  }
Run Code Online (Sandbox Code Playgroud)

另外的System.Exception有一个HRESULT

 catch (Exception ex){  
     int code = ex.HResult;
 }
Run Code Online (Sandbox Code Playgroud)

但是它只能从.net 4.5以上获得.


小智 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
     }
 }
Run Code Online (Sandbox Code Playgroud)

...

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;
}
Run Code Online (Sandbox Code Playgroud)

该代码已经过单元测试。

当涉及到异常处理时,我不会过多地强调通过在自己的块中管理每个预期的异常类型来欣赏和实施良好实践的必要性。