microsoft / cppwinrt

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

Opt-in inheritance from std::exception for winrt::hresult_error #1367

Closed JaiganeshKumaran closed 10 months ago

JaiganeshKumaran commented 10 months ago

Related to #1336, #1129 and #207.

Currently winrt::hresult_error does not inherit from std::exception. When writing cross-platform applications that may use C++/WinRT internally on Windows, one would except that they could catch std::exception to catch all exceptions with error message. Today I need an extra layer to convert an HRESULT to the appropriate std::exception-derived type so the calling code, for example, can just catch std::invalid_argument instead of needing to know about winrt::hresult_invalid_argument.

For the error message, I would recommend lazily converting the hstring into a UTF-8 encoded std::string if winrt::hresult gets inherited from std::exception.

kennykerr commented 10 months ago

This was considered and rejected years ago. Here are some of the reasons:

https://github.com/microsoft/cppwinrt/issues/207#issuecomment-308500627

JaiganeshKumaran commented 10 months ago

It would also force calls into the CRT from both constructor and destructor - all to produce a message that lacks much of the richness of WinRT's error information.

You do not have to use the constructor and in fact, std::exception does not have a constructor taking error message (Microsoft's implementation does but that is non-standard) - only std::runtime_error and logic_error do. Instead, override the virtual what method and lazily convert the error message to UTF-8. This should not have much overhead.

Also the constructor of std::exception is just an inline function (at least in MSVC) so no calls into the CRT is required.

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.