0

I have a web service. Within a method, I have a try-catch block. Then within it, I would like to get the exception code.

I have tried below:

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   
}

... that is explained here but in my case, it is not working: When casting exception e as Win32Exception I get a null and also once I get a null and I try to cast e.InnerException as Win32Exception I get null as well.

Below a screenshot with my exception:

enter image description here

As you can see there is a HResult code.

YosiFZ
  • 7,792
  • 21
  • 114
  • 221
Willy
  • 9,848
  • 22
  • 141
  • 284

1 Answers1

0

According to your screenshot, you're catching an instance of SoapException: https://learn.microsoft.com/en-us/dotnet/api/system.web.services.protocols.soapexception?view=netframework-3.5 This class doesn't inherit from Win32Exception, that's why the type cast operator returns null. You should be able to get HResult field right from the base Exception class (even in .Net 3.5, according to the docs):

catch (Win32Exception w32ex)
{  
    // Put your current code here...
}
catch (Exception ex)
{
    int hResult = ex.HResult;
    // Handle HRESULT error code here...   
}
johnnyjob
  • 380
  • 1
  • 9
  • Could you provide a code snippet on how to get error code? I have tried without success. – Willy Mar 12 '19 at 10:09
  • @user1624552 Why do you need this "error code"? What are you trying to catch here? – spender Mar 12 '19 at 10:18
  • Because I need to do some stuff only when this type of error is thrown. Exception can be the same but error codes can vary. so I need to identify exactly what error code is. – Willy Mar 12 '19 at 10:22
  • .. and Yes, you are right, the exception that is thrown is of type System.Web.Services.Protocols.SoapException so how can I get the error code from there? – Willy Mar 12 '19 at 10:45
  • @user1624552 I added the code snippet to the answer. – johnnyjob Mar 12 '19 at 13:08