通过从C#COM互操作提升积极的VB风格的错误codeS [英] Raise positive VB style error codes via COM interop from C#

查看:216
本文介绍了通过从C#COM互操作提升积极的VB风格的错误codeS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VB6创建的基本库暴露是,用于在多个应用程序的标准COM接口。 这也暴露了一些错误code常数,与 Err.Raise 用来表示一定的条件。

I have a base library created in VB6 that exposes a standard COM interface that is used in a number of applications. This also exposed a number of error code constants, used with Err.Raise to indicate certain conditions.

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

来吧10年,我们要创建实现同一组接口C#对象,并希望抛出异常的方式,调用应用程序会识别它们。

Come on 10 years and we're creating C# objects implementing the same set of interfaces and want to throw exceptions in a way that the calling application will recognise them.

我只能找到两个相关的类, Win32Exception 收到COMException

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

投掷 Win32Exception((INT)IOErrors.IOErrorConnectionFailed,连接失败)将消息传递回正常,但错误code被忽略,的Err.Number &放大器; H80004005

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

投掷收到COMException(连接失败,IOErrors.IOErrorConnectionFailed)的结果没有错误被拾起在调用应用程序,presumably因为错误code不为 HRESULT ,是积极的,这意味着成功。

Throwing COMException("Connect failed", IOErrors.IOErrorConnectionFailed) results in no error being picked up in the calling application, presumably because the error code is not an HRESULT and is positive, meaning success.

TL; DR 我怎么能扔从C#,使得COM互操作将它翻译成公认的(积极的)错误codeS上面?一个例外

TL;DR How can I throw an exception from C# such that COM interop will translate it into one of the recognised (positive) error codes above?

推荐答案

正VB风格的错误号将被转换为 HRESULT s的一个失败的严重性和一个设施 FACILITY_CONTROL / 为0xA ,即 0x800AAFC9

The "positive" VB style error numbers are translated to HRESULTs with a "FAILURE" severity and a facility of FACILITY_CONTROL/0xA, i.e. 0x800AAFC9.

您可以得到一个合适的 HRESULT 使用:

You can get a suitable HRESULT using:

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

这可以被提高回用普通的收到COMException 调用进程,或通过抛出收到COMException

This can then be raised back to the calling process using a plain 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);
    }
}

这篇关于通过从C#COM互操作提升积极的VB风格的错误codeS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆