Increase positive VB style error codes through COM interaction with C #

I have a base library created in VB6 that provides a standard COM interface that is used in a number of applications. It also revealed a number of error code constants used with Err.Raise to indicate specific conditions.

 Public Enum IOErrors IOErrorBase = 45000 IOErrorConnectionFailed IOErrorAuthFailed IOErrorNotConnected IOErrorInvalidPortDirection IOErrorGettingValue IOErrorNoValueYet End Enum 

Come for 10 years, and we create C # objects that implement the same set of interfaces, and we want to throw exceptions so that the calling application recognizes them.

I can only find two corresponding classes, Win32Exception and COMException .

Throwing Win32Exception((int)IOErrors.IOErrorConnectionFailed, "Connect failed") correctly transmits the message, but the error code is ignored, and Err.Number is &H80004005 .

Throwing COMException("Connect failed", IOErrors.IOErrorConnectionFailed) does not cause an error in the calling application, apparently because the error code is not HRESULT and is positive, which means success.

TL DR How can I throw an exception from C # so that COM-interop translates it into one of the recognized (positive) error codes above?

+3
source share
1 answer

The โ€œpositiveโ€ VB-style error numbers were translated to HRESULT with the severity of โ€œFAILUREโ€ and the FACILITY_CONTROL / 0xA , that is, 0x800AAFC9 .

You can get the appropriate HRESULT using:

 int HResult = (int)(0x800A0000 | (int)errorCode); 

This can then be returned back to the calling process using a simple COMException or by throwing your own subclass of COMException :

 /// <summary> /// Exception that returns an ICIO error wrapped in an exception. /// </summary> internal class ICIOErrorException : COMException { internal ICIOErrorException(ICIO.IOErrors errorCode, string message) : base(message) { this.HResult = (int)(0x800A0000 | (int)errorCode); } } 
+4
source

Source: https://habr.com/ru/post/944564/


All Articles