How to get Exception Error Code in C#

前端 未结 5 1162
心在旅途
心在旅途 2020-11-30 08:57
try
{
     object result = processClass.InvokeMethod(\"Create\", methodArgs);
}
catch (Exception e)
{  
    // Here I was hoping to get an error code.
}
5条回答
  •  天命终不由人
    2020-11-30 09:27

    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.

     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.

提交回复
热议问题