{"id":108956,"date":"2023-11-02T07:00:00","date_gmt":"2023-11-02T14:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=108956"},"modified":"2023-11-02T07:04:54","modified_gmt":"2023-11-02T14:04:54","slug":"20231102-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20231102-00\/?p=108956","title":{"rendered":"How come my custom exception message is lost when it is thrown from a <CODE>IAsyncAction^<\/CODE>?"},"content":{"rendered":"<p>A customer implemented an <code>IAsyncAction^<\/code> using the Parallel Patterns Library (PPL). They had the action throw an exception with a custom message, but found that the custom message was lost when they tried to catch it:<\/p>\n<pre>IAsyncAction^ DoSomething()\r\n{\r\n    return concurrency::create_async([] {\r\n        throw ref new Platform::Exception(E_FAIL, \"Sorry!\");\r\n    });\r\n}\r\n\r\n\/\/ consumer\r\nconcurrency::create_task(DoSomething())\r\n.then([](concurrency::task&lt;void&gt; precedingTask) {\r\n    try {\r\n        precedingTask.get();\r\n    } catch (Platform::Exception^ ex) {\r\n        printf(\"0x%08x %ls\\n\",\r\n            ex-&gt;HResult,\r\n            ex-&gt;Message-&gt;Data());\r\n    }\r\n});\r\n<\/pre>\n<p>This code successfully catches the exception, and the <code>HResult<\/code> is preserved, but the custom message is lost.<\/p>\n<p>What&#8217;s going on?<\/p>\n<p>Recall that at the ABI layer, the only way to report an error from an <code>IAsyncAction<\/code> is through an <code>HRESULT<\/code>. You can retrieve it by reading the <code>ErrorCode<\/code> property, or you can experience it live by calling <code>GetResults()<\/code> method and receiving the error as the failure code.<\/p>\n<p>Now, there is a side channel mechanism for providing additional information: The <code>Ro\u00adOriginate\u00adError<\/code> function lets you attach a message to a failure, which is stored in the thread context, and some libraries like C++\/WinRT sets and retrieves this context when it generates and reconstructs a <code>hresult_<wbr \/>error<\/code> object.<\/p>\n<p>But let&#8217;s see what PPL does when a C++\/CX exception occurs:<\/p>\n<pre>    \/\/ ppltasks.h\r\n    template&lt;typename _Function&gt;\r\n    ref class _AsyncTaskGeneratorThunk sealed :\r\n        _AsyncProgressBase&lt;typename _AsyncLambdaTypeTraits&lt;_Function&gt;::_AsyncAttributes,\r\n        _AsyncLambdaTypeTraits&lt;_Function&gt;::_AsyncAttributes::_TakesProgress&gt;\r\n    {\r\n        \u27e6\u2026\u27e7\r\n\r\n        virtual void _OnStart() override\r\n        {\r\n            _M_task = _AsyncAttributesTaskGenerator::\r\n                _Generate_Task&lt;_Function, _AsyncTaskGeneratorThunk&lt;_Function&gt;^,\r\n                    _Attributes&gt;(_M_func, this, _M_cts, _M_creationCallstack);\r\n            _M_task.then([=](task&lt;typename _Attributes::_ReturnType&gt; _Antecedent) {\r\n                try\r\n                {\r\n                    _Antecedent.get();\r\n                }\r\n                catch (task_canceled&amp;)\r\n                {\r\n                    this-&gt;_TryTransitionToCancelled();\r\n                }\r\n                <span style=\"border: solid 1px currentcolor; border-bottom: none;\">catch (::Platform::Exception^ _Ex)            <\/span>\r\n                <span style=\"border: 1px currentcolor; border-style: none solid;\">{                                             <\/span>\r\n                <span style=\"border: 1px currentcolor; border-style: none solid;\">    this-&gt;_TryTransitionToError(_Ex-&gt;HResult);<\/span>\r\n                <span style=\"border: solid 1px currentcolor; border-top: none;\">}                                             <\/span>\r\n                catch (...)\r\n                {\r\n                    this-&gt;_TryTransitionToError(E_FAIL);\r\n                }\r\n                this-&gt;_FireCompletion();\r\n            });\r\n        }\r\n        \u27e6\u2026\u27e7\r\n    };\r\n<\/pre>\n<p>Observe that when a C++\/CX exception is thrown from the lambda, the exception&#8217;s <code>HResult<\/code> is passed to <code>_Try\u00adTransition\u00adTo\u00adError<\/code>, but all the other details are ignored. The PPL library doesn&#8217;t call <code>Ro\u00adOriginate\u00adError<\/code>, or <code>Get\u00adError\u00adInfo<\/code>, so it doesn&#8217;t use the side channel for conveying additional failure information. All that survives is the <code>HRESULT<\/code>.<\/p>\n<p>Now, if <code>Do\u00adSomething<\/code> is a function internal to your project, then you can change it to return a <code>concurrency::<wbr \/>task&lt;void&gt;<\/code>. The PPL library preserves exceptions thrown from <code>tasks<\/code>, and rethrows them when you call <code>.get()<\/code>.<\/p>\n<pre>IAsyncAction^ DoSomething()\r\n{\r\n    return concurrency::create_<span style=\"border: solid 1px currentcolor;\">task<\/span>([] {\r\n        throw ref new Platform::Exception(E_FAIL, \"Sorry!\");\r\n    });\r\n}\r\n\r\n\/\/ consumer\r\n<span style=\"border: solid 1px currentcolor;\">DoSomething()<\/span>\r\n.then([](concurrency::task&lt;void&gt; precedingTask) {\r\n    try {\r\n        precedingTask.get();\r\n    } catch (Platform::Exception^ ex) {\r\n        printf(\"0x%08x %ls\\n\",\r\n            ex-&gt;HResult,\r\n            ex-&gt;Message-&gt;Data());\r\n    }\r\n});\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Things that survive in the C++ world and things that are lost when you cross the ABI.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-108956","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Things that survive in the C++ world and things that are lost when you cross the ABI.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/108956","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=108956"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/108956\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=108956"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=108956"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=108956"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}