简体   繁体   English

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

[英]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.
}

When I invoke the above WMI method I am expected to get Access Denied.当我调用上述 WMI 方法时,我预计会被拒绝访问。 In my catch block I want to make sure that the exception raised was indeed for Access Denied.在我的 catch 块中,我想确保引发的异常确实是针对拒绝访问的。 Is there a way I can get the error code for it ?有什么办法可以得到它的错误代码吗? Win32 error code for Acceess Denied is 5. I dont want to search the error message for denied string or anything like that. Access Denied 的 Win32 错误代码是 5。我不想在错误消息中搜索被拒绝的字符串或类似内容。

Thanks谢谢

You can use this to check the exception and the inner exception for a Win32Exception derived exception.您可以使用它来检查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   
}

Starting with C# 6, when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.从 C# 6 开始,可以在 catch 语句中使用when来指定一个条件,该条件对于要执行的特定异常的处理程序来说必须为真。

catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
    var w32ex = (Win32Exception)ex.InnerException;
    var code =  w32ex.ErrorCode;
}

As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception.正如在评论中一样,您确实需要查看实际抛出的异常以了解您可以做什么,并且在这种情况下,特定的捕获优于仅捕获异常。 Something like:就像是:

  catch (BlahBlahException ex) {  
      // do stuff   
  }

Also System.Exception has a HRESULT System.Exception 也有一个 HRESULT

 catch (Exception ex) {  
     var code = ex.HResult;
 }

However, it's only available from .NET 4.5 upwards.但是,它仅适用于 .NET 4.5 以上。

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.以 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;
}

This code has been unit tested.此代码已经过单元测试。

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.通过在自己的块中管理每个预期的异常类型,我不会过多强调在异常处理方面需要了解和实施良好实践。

You should look at the members of the thrown exception, particularly .Message and .InnerException .您应该查看抛出异常的成员,特别是.Message.InnerException

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet.我还将查看 InvokeMethod 的文档是否告诉您它是否抛出一些比 Exception 更专业的 Exception 类 - 例如 @Preet 建议的 Win32Exception。 Catching and just looking at the Exception base class may not be particularly useful.捕获并仅查看 Exception 基类可能不是特别有用。

I suggest you to use Message Properte from The Exception Object Like below code我建议你使用来自异常对象的消息属性如下代码

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
}

Another method would be to get the error code from the exception class directly.另一种方法是直接从异常类中获取错误代码。 For example:例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM