microsoft / cppwinrt

C++/WinRT
MIT License
1.64k stars 236 forks source link

How to map custom exception type to an HRESULT? #1366

Closed JaiganeshKumaran closed 10 months ago

JaiganeshKumaran commented 10 months ago

I have a few custom exception types that need to reported with a custom HRESULT from a Windows Runtime component. I notice that there is winrt_to_hresult_handler but that won't really work in my case; I only need to handle a few exception types and then leave the reset to be handled by C++/WinRT, however, overriding the handler implies that you have to handle all exception types. Also another library (example: WIL) may have already overridden the handler, so me overriding it will prevent those exceptions being reported correctly, unless I take care to dispatch into them.

JaiganeshKumaran commented 10 months ago

Another idea I have is to make these custom exceptions inherit from a C++/WinRT exception type. For example, I have a custom not_implements class, which could inherit from hresult_not_implements on Windows. Though there is a downside of having to construct an hstring immediately.

JaiganeshKumaran commented 10 months ago

Here's another idea - provide a custom base class with a virtual function to convert the exception to an hresult_error.

struct convertible_to_hresult_error
{
    virtual winrt::hresult_error get_hresult_error();
}:
kennykerr commented 10 months ago

Exception types are not extensible in C++/WinRT.

JaiganeshKumaran commented 10 months ago

Exception types are not extensible in C++/WinRT.

But I do want to have my own exception types whose information can be transferred across components with a custom HRESULT. I do not want to it to be reported as E_FAIL.

kennykerr commented 10 months ago

You could serialize your exception type and transport it via ILanguageExceptionErrorInfo2 after creating a winrt::hresult_error. You can query for this interface using try_as.

github-actions[bot] commented 10 months ago

This issue is stale because it has been open 10 days with no activity. Remove stale label or comment or this will be closed in 5 days.