-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathExceptionHelpers.cs
718 lines (647 loc) · 31.4 KB
/
ExceptionHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using WinRT.Interop;
namespace WinRT
{
#if EMBED
internal
#else
public
#endif
static unsafe class ExceptionHelpers
{
private const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
private const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153b);
private const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
private const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
private const int COR_E_TIMEOUT = unchecked((int)0x80131505);
private const int RO_E_CLOSED = unchecked((int)0x80000013);
internal const int E_BOUNDS = unchecked((int)0x8000000b);
internal const int E_CHANGED_STATE = unchecked((int)0x8000000c);
private const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000d);
private const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000e);
private const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018);
private const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54);
internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A);
internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014);
internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E);
internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F);
internal const int ERROR_INVALID_WINDOW_HANDLE = unchecked((int)0x80070578);
private const int E_POINTER = unchecked((int)0x80004003);
private const int E_NOTIMPL = unchecked((int)0x80004001);
private const int E_ACCESSDENIED = unchecked((int)0x80070005);
private const int E_INVALIDARG = unchecked((int)0x80070057);
private const int E_NOINTERFACE = unchecked((int)0x80004002);
private const int E_OUTOFMEMORY = unchecked((int)0x8007000e);
private const int ERROR_ARITHMETIC_OVERFLOW = unchecked((int)0x80070216);
private const int ERROR_FILENAME_EXCED_RANGE = unchecked((int)0x800700ce);
private const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002);
private const int ERROR_HANDLE_EOF = unchecked((int)0x80070026);
private const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003);
private const int ERROR_STACK_OVERFLOW = unchecked((int)0x800703e9);
private const int ERROR_BAD_FORMAT = unchecked((int)0x8007000b);
private const int ERROR_CANCELLED = unchecked((int)0x800704c7);
private const int ERROR_TIMEOUT = unchecked((int)0x800705b4);
[DllImport("oleaut32.dll")]
private static extern int SetErrorInfo(uint dwReserved, IntPtr perrinfo);
private static delegate* unmanaged[Stdcall]<IntPtr*, int> getRestrictedErrorInfo;
private static delegate* unmanaged[Stdcall]<IntPtr, int> setRestrictedErrorInfo;
private static delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr, int> roOriginateLanguageException;
private static delegate* unmanaged[Stdcall]<IntPtr, int> roReportUnhandledError;
private static readonly bool initialized = Initialize();
private static bool Initialize()
{
IntPtr winRTErrorModule = Platform.LoadLibraryExW("api-ms-win-core-winrt-error-l1-1-1.dll", IntPtr.Zero, (uint)DllImportSearchPath.System32);
if (winRTErrorModule != IntPtr.Zero)
{
#if NET7_0_OR_GREATER || CsWinRT_LANG_11_FEATURES
ReadOnlySpan<byte> langExceptionString = "RoOriginateLanguageException"u8;
ReadOnlySpan<byte> reportUnhandledErrorString = "RoReportUnhandledError"u8;
#else
string langExceptionString = "RoOriginateLanguageException";
string reportUnhandledErrorString = "RoReportUnhandledError";
#endif
roOriginateLanguageException = (delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, langExceptionString);
roReportUnhandledError = (delegate* unmanaged[Stdcall]<IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, reportUnhandledErrorString);
}
else
{
winRTErrorModule = Platform.LoadLibraryExW("api-ms-win-core-winrt-error-l1-1-0.dll", IntPtr.Zero, (uint)DllImportSearchPath.System32);
}
if (winRTErrorModule != IntPtr.Zero)
{
#if NET7_0_OR_GREATER || CsWinRT_LANG_11_FEATURES
ReadOnlySpan<byte> getRestrictedErrorInfoFuncName = "GetRestrictedErrorInfo"u8;
ReadOnlySpan<byte> setRestrictedErrorInfoFuncName = "SetRestrictedErrorInfo"u8;
#else
string getRestrictedErrorInfoFuncName = "GetRestrictedErrorInfo";
string setRestrictedErrorInfoFuncName = "SetRestrictedErrorInfo";
#endif
getRestrictedErrorInfo = (delegate* unmanaged[Stdcall]<IntPtr*, int>)Platform.GetProcAddress(winRTErrorModule, getRestrictedErrorInfoFuncName);
setRestrictedErrorInfo = (delegate* unmanaged[Stdcall]<IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, setRestrictedErrorInfoFuncName);
}
return true;
}
/// <summary>
/// Unhandled WinRT server exception event.
/// </summary>
public static event EventHandler<UnhandledWinRTServerExceptionEventArgs> UnhandledWinRTServerException;
public class UnhandledWinRTServerExceptionEventArgs : EventArgs
{
public Exception Exception { get; }
public bool Handled { get; set; }
public UnhandledWinRTServerExceptionEventArgs(Exception exception)
{
Exception = exception;
}
}
public static int HandleWinRTServerException(object sender, Exception ex, bool dispatchExceptionToUnmanagedCode)
{
EventHandler<UnhandledWinRTServerExceptionEventArgs> handler = UnhandledWinRTServerException;
if (handler != null)
{
UnhandledWinRTServerExceptionEventArgs args = new(ex);
handler.Invoke(sender, args);
if (args.Handled)
{
return 0;
}
}
if (dispatchExceptionToUnmanagedCode)
{
SetErrorInfo(ex);
return GetHRForException(ex);
}
else
{
return ex.HResult;
}
}
public static void ThrowExceptionForHR(int hr)
{
if (hr < 0)
{
Throw(hr);
}
static void Throw(int hr)
{
Exception ex = GetExceptionForHR(hr, useGlobalErrorState: true, out bool restoredExceptionFromGlobalState);
if (restoredExceptionFromGlobalState)
{
ExceptionDispatchInfo.Capture(ex).Throw();
}
else
{
throw ex;
}
}
}
// Retrieve restricted error info from thread without removing it, for propagation and debugging (watch, locals, etc)
private static IObjectReference BorrowRestrictedErrorInfo()
{
if (getRestrictedErrorInfo == null)
return null;
IntPtr restrictedErrorInfoPtr = IntPtr.Zero;
Marshal.ThrowExceptionForHR(getRestrictedErrorInfo(&restrictedErrorInfoPtr));
if (restrictedErrorInfoPtr == IntPtr.Zero)
return null;
if (setRestrictedErrorInfo != null)
{
setRestrictedErrorInfo(restrictedErrorInfoPtr);
return ObjectReference<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>.FromAbi(restrictedErrorInfoPtr);
}
return ObjectReference<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>.Attach(ref restrictedErrorInfoPtr);
}
public static Exception GetExceptionForHR(int hr) => hr >= 0 ? null : GetExceptionForHR(hr, true, out _);
private static Exception GetExceptionForHR(int hr, bool useGlobalErrorState, out bool restoredExceptionFromGlobalState)
{
restoredExceptionFromGlobalState = false;
IObjectReference restrictedErrorInfoToSave = null;
Exception ex;
string description = null;
string restrictedError = null;
string restrictedErrorReference = null;
string restrictedCapabilitySid = null;
bool hasOtherLanguageException = false;
string errorMessage = string.Empty;
if (useGlobalErrorState)
{
using var restrictedErrorInfoRef = BorrowRestrictedErrorInfo();
if (restrictedErrorInfoRef != null)
{
restrictedErrorInfoToSave = restrictedErrorInfoRef.As<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>();
ABI.WinRT.Interop.IRestrictedErrorInfo restrictedErrorInfo = new ABI.WinRT.Interop.IRestrictedErrorInfo(restrictedErrorInfoRef);
restrictedErrorInfo.GetErrorDetails(out description, out int hrLocal, out restrictedError, out restrictedCapabilitySid);
restrictedErrorReference = restrictedErrorInfo.GetReference();
if (restrictedErrorInfoRef.TryAs<ABI.WinRT.Interop.ILanguageExceptionErrorInfo.Vftbl>(out var languageErrorInfoRef) >= 0)
{
ILanguageExceptionErrorInfo languageErrorInfo = new ABI.WinRT.Interop.ILanguageExceptionErrorInfo(languageErrorInfoRef);
using IObjectReference languageException = languageErrorInfo.GetLanguageException();
if (languageException is object)
{
if (languageException.IsReferenceToManagedObject)
{
ex = ComWrappersSupport.FindObject<Exception>(languageException.ThisPtr);
if (GetHRForException(ex) == hr)
{
restoredExceptionFromGlobalState = true;
return ex;
}
}
else
{
// This could also be a proxy to a managed exception.
hasOtherLanguageException = true;
}
}
}
if (hr == hrLocal)
{
// For cross language WinRT exceptions, general information will be available in the description,
// which is populated from IRestrictedErrorInfo::GetErrorDetails and more specific information will be available
// in the restrictedError which also comes from IRestrictedErrorInfo::GetErrorDetails. If both are available, we
// need to concatinate them to produce the final exception message.
if (!string.IsNullOrEmpty(description))
{
errorMessage += description;
if (!string.IsNullOrEmpty(restrictedError))
{
errorMessage += Environment.NewLine;
}
}
if (!string.IsNullOrEmpty(restrictedError))
{
errorMessage += restrictedError;
}
}
}
}
switch (hr)
{
case E_CHANGED_STATE:
case E_ILLEGAL_STATE_CHANGE:
case E_ILLEGAL_METHOD_CALL:
case E_ILLEGAL_DELEGATE_ASSIGNMENT:
case APPMODEL_ERROR_NO_PACKAGE:
ex = !string.IsNullOrEmpty(errorMessage) ? new InvalidOperationException(errorMessage) : new InvalidOperationException();
break;
case E_XAMLPARSEFAILED:
ex = !string.IsNullOrEmpty(errorMessage) ? new Microsoft.UI.Xaml.Markup.XamlParseException(errorMessage) : new Microsoft.UI.Xaml.Markup.XamlParseException();
break;
case E_LAYOUTCYCLE:
ex = !string.IsNullOrEmpty(errorMessage) ? new Microsoft.UI.Xaml.LayoutCycleException(errorMessage) : new Microsoft.UI.Xaml.LayoutCycleException();
break;
case E_ELEMENTNOTAVAILABLE:
ex = !string.IsNullOrEmpty(errorMessage) ? new Microsoft.UI.Xaml.Automation.ElementNotAvailableException(errorMessage) : new Microsoft.UI.Xaml.Automation.ElementNotAvailableException();
break;
case E_ELEMENTNOTENABLED:
ex = !string.IsNullOrEmpty(errorMessage) ? new Microsoft.UI.Xaml.Automation.ElementNotEnabledException(errorMessage) : new Microsoft.UI.Xaml.Automation.ElementNotEnabledException();
break;
case ERROR_INVALID_WINDOW_HANDLE:
ex = new COMException(
@"Invalid window handle. (0x80070578)
Consider WindowNative, InitializeWithWindow
See https://aka.ms/cswinrt/interop#windows-sdk",
ERROR_INVALID_WINDOW_HANDLE);
break;
case RO_E_CLOSED:
ex = !string.IsNullOrEmpty(errorMessage) ? new ObjectDisposedException(string.Empty, errorMessage) : new ObjectDisposedException(string.Empty);
break;
case E_POINTER:
ex = !string.IsNullOrEmpty(errorMessage) ? new NullReferenceException(errorMessage) : new NullReferenceException();
break;
case E_NOTIMPL:
ex = !string.IsNullOrEmpty(errorMessage) ? new NotImplementedException(errorMessage) : new NotImplementedException();
break;
case E_ACCESSDENIED:
ex = !string.IsNullOrEmpty(errorMessage) ? new UnauthorizedAccessException(errorMessage) : new UnauthorizedAccessException();
break;
case E_INVALIDARG:
ex = !string.IsNullOrEmpty(errorMessage) ? new ArgumentException(errorMessage) : new ArgumentException();
break;
case E_NOINTERFACE:
ex = !string.IsNullOrEmpty(errorMessage) ? new InvalidCastException(errorMessage) : new InvalidCastException();
break;
case E_OUTOFMEMORY:
ex = !string.IsNullOrEmpty(errorMessage) ? new OutOfMemoryException(errorMessage) : new OutOfMemoryException();
break;
case E_BOUNDS:
ex = !string.IsNullOrEmpty(errorMessage) ? new ArgumentOutOfRangeException(errorMessage) : new ArgumentOutOfRangeException();
break;
case ERROR_ARITHMETIC_OVERFLOW:
ex = !string.IsNullOrEmpty(errorMessage) ? new ArithmeticException(errorMessage) : new ArithmeticException();
break;
case ERROR_FILENAME_EXCED_RANGE:
ex = !string.IsNullOrEmpty(errorMessage) ? new PathTooLongException(errorMessage) : new PathTooLongException();
break;
case ERROR_FILE_NOT_FOUND:
ex = !string.IsNullOrEmpty(errorMessage) ? new FileNotFoundException(errorMessage) : new FileNotFoundException();
break;
case ERROR_HANDLE_EOF:
ex = !string.IsNullOrEmpty(errorMessage) ? new EndOfStreamException(errorMessage) : new EndOfStreamException();
break;
case ERROR_PATH_NOT_FOUND:
ex = !string.IsNullOrEmpty(errorMessage) ? new DirectoryNotFoundException(errorMessage) : new DirectoryNotFoundException();
break;
case ERROR_STACK_OVERFLOW:
ex = !string.IsNullOrEmpty(errorMessage) ? new StackOverflowException(errorMessage) : new StackOverflowException();
break;
case ERROR_BAD_FORMAT:
ex = !string.IsNullOrEmpty(errorMessage) ? new BadImageFormatException(errorMessage) : new BadImageFormatException();
break;
case ERROR_CANCELLED:
ex = !string.IsNullOrEmpty(errorMessage) ? new OperationCanceledException(errorMessage) : new OperationCanceledException();
break;
case ERROR_TIMEOUT:
ex = !string.IsNullOrEmpty(errorMessage) ? new TimeoutException(errorMessage) : new TimeoutException();
break;
default:
ex = new COMException(errorMessage, hr);
break;
}
// Ensure HResult matches.
ex.SetHResult(hr);
if (useGlobalErrorState)
{
ex.AddExceptionDataForRestrictedErrorInfo(
description,
restrictedError,
restrictedErrorReference,
restrictedCapabilitySid,
restrictedErrorInfoToSave,
hasOtherLanguageException);
}
return ex;
}
public static unsafe void SetErrorInfo(Exception ex)
{
if (getRestrictedErrorInfo != null && setRestrictedErrorInfo != null && roOriginateLanguageException != null)
{
// If the exception has information for an IRestrictedErrorInfo, use that
// as our error so as to propagate the error through WinRT end-to-end.
if (ex.TryGetRestrictedLanguageErrorObject(out var restrictedErrorObject))
{
using (restrictedErrorObject)
{
setRestrictedErrorInfo(restrictedErrorObject.ThisPtr);
}
}
else
{
string message = ex.Message;
if (string.IsNullOrEmpty(message))
{
message = ex.GetType().FullName;
}
IntPtr hstring;
fixed (char* lpMessage = message)
{
if (Platform.WindowsCreateString((ushort*)lpMessage, message.Length, &hstring) != 0)
{
hstring = IntPtr.Zero;
}
}
using var managedExceptionWrapper = ComWrappersSupport.CreateCCWForObject(ex);
roOriginateLanguageException(GetHRForException(ex), hstring, managedExceptionWrapper.ThisPtr);
}
}
else
{
using var iErrorInfo = ComWrappersSupport.CreateCCWForObject(new ManagedExceptionErrorInfo(ex));
SetErrorInfo(0, iErrorInfo.ThisPtr);
}
}
public static void ReportUnhandledError(Exception ex)
{
SetErrorInfo(ex);
if (roReportUnhandledError != null)
{
var restrictedErrorInfoRef = BorrowRestrictedErrorInfo();
if (restrictedErrorInfoRef != null)
{
roReportUnhandledError(restrictedErrorInfoRef.ThisPtr);
}
}
}
public static int GetHRForException(Exception ex)
{
int hr = ex.HResult;
if (ex.TryGetRestrictedLanguageErrorObject(out var restrictedErrorObject))
{
restrictedErrorObject.AsType<ABI.WinRT.Interop.IRestrictedErrorInfo>().GetErrorDetails(out _, out hr, out _, out _);
}
switch (hr)
{
case COR_E_OBJECTDISPOSED:
return RO_E_CLOSED;
case COR_E_OPERATIONCANCELED:
return ERROR_CANCELLED;
case COR_E_ARGUMENTOUTOFRANGE:
case COR_E_INDEXOUTOFRANGE:
return E_BOUNDS;
case COR_E_TIMEOUT:
return ERROR_TIMEOUT;
default:
return hr;
}
}
//
// Exception requires anything to be added into Data dictionary is serializable
// This wrapper is made serializable to satisfy this requirement but does NOT serialize
// the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
//
[Serializable]
internal sealed class __RestrictedErrorObject
{
// Hold the error object instance but don't serialize/deserialize it
[NonSerialized]
private readonly IObjectReference _realErrorObject;
internal __RestrictedErrorObject(IObjectReference errorObject)
{
_realErrorObject = errorObject;
}
public IObjectReference RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
internal static void AddExceptionDataForRestrictedErrorInfo(
this Exception ex,
string description,
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
IObjectReference restrictedErrorObject,
bool hasRestrictedLanguageErrorObject = false)
{
IDictionary dict = ex.Data;
if (dict != null)
{
dict["Description"] = description;
dict["RestrictedDescription"] = restrictedError;
dict["RestrictedErrorReference"] = restrictedErrorReference;
dict["RestrictedCapabilitySid"] = restrictedCapabilitySid;
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict["__RestrictedErrorObjectReference"] = restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject);
dict["__HasRestrictedLanguageErrorObject"] = hasRestrictedLanguageErrorObject;
}
}
internal static bool TryGetRestrictedLanguageErrorObject(
this Exception ex,
out IObjectReference restrictedErrorObject)
{
restrictedErrorObject = null;
IDictionary dict = ex.Data;
if (dict != null && dict.Contains("__HasRestrictedLanguageErrorObject"))
{
if (dict.Contains("__RestrictedErrorObjectReference"))
{
if (dict["__RestrictedErrorObjectReference"] is __RestrictedErrorObject restrictedObject)
restrictedErrorObject = restrictedObject.RealErrorObject;
}
return (bool)dict["__HasRestrictedLanguageErrorObject"]!;
}
return false;
}
public static Exception AttachRestrictedErrorInfo(Exception e)
{
// If there is no exception, then the restricted error info doesn't apply to it
if (e != null)
{
try
{
// Get the restricted error info for this thread and see if it may correlate to the current
// exception object. Note that in general the thread's IRestrictedErrorInfo is not meant for
// exceptions that are marshaled Windows.Foundation.HResults and instead are intended for
// HRESULT ABI return values. However, in many cases async APIs will set the thread's restricted
// error info as a convention in order to provide extended debugging information for the ErrorCode
// property.
IntPtr restrictedErrorInfoPtr = IntPtr.Zero;
Marshal.ThrowExceptionForHR(getRestrictedErrorInfo(&restrictedErrorInfoPtr));
if (restrictedErrorInfoPtr != IntPtr.Zero)
{
IObjectReference restrictedErrorInfoRef = ObjectReference<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>.Attach(ref restrictedErrorInfoPtr);
ABI.WinRT.Interop.IRestrictedErrorInfo restrictedErrorInfo = new ABI.WinRT.Interop.IRestrictedErrorInfo(restrictedErrorInfoRef);
restrictedErrorInfo.GetErrorDetails(out string description,
out int restrictedErrorInfoHResult,
out string restrictedDescription,
out string capabilitySid);
// Since this is a special case where by convention there may be a correlation, there is not a
// guarantee that the restricted error info does belong to the async error code. In order to
// reduce the risk that we associate incorrect information with the exception object, we need
// to apply a heuristic where we attempt to match the current exception's HRESULT with the
// HRESULT the IRestrictedErrorInfo belongs to. If it is a match we will assume association
// for the IAsyncInfo case.
if (e.HResult == restrictedErrorInfoHResult)
{
e.AddExceptionDataForRestrictedErrorInfo(description,
restrictedDescription,
restrictedErrorInfo.GetReference(),
capabilitySid,
restrictedErrorInfoRef.As<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>());
}
}
}
catch
{
// If we can't get the restricted error info, then proceed as if it isn't associated with this
// error.
}
}
return e;
}
}
#if EMBED
internal
#else
public
#endif
static class ExceptionExtensions
{
public static void SetHResult(this Exception ex, int value)
{
#if !NET
ex.GetType().GetProperty("HResult").SetValue(ex, value);
#else
ex.HResult = value;
#endif
}
internal static Exception GetExceptionForHR(this Exception innerException, int hresult, string messageResource)
{
Exception e;
if (innerException != null)
{
string message = innerException.Message ?? messageResource;
e = new Exception(message, innerException);
}
else
{
e = new Exception(messageResource);
}
e.SetHResult(hresult);
return e;
}
}
}
namespace Microsoft.UI.Xaml
{
using System.Runtime.Serialization;
namespace Automation
{
[Serializable]
#if EMBED
internal
#else
public
#endif
class ElementNotAvailableException : Exception
{
public ElementNotAvailableException()
: base("The element is not available.")
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
public ElementNotAvailableException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
public ElementNotAvailableException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
protected ElementNotAvailableException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
#if EMBED
internal
#else
public
#endif
class ElementNotEnabledException : Exception
{
public ElementNotEnabledException()
: base("The element is not enabled.")
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
public ElementNotEnabledException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
public ElementNotEnabledException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
}
}
namespace Markup
{
#if EMBED
internal
#else
public
#endif
class XamlParseException : Exception
{
public XamlParseException()
: base("XAML parsing failed.")
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
public XamlParseException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
public XamlParseException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
}
}
[Serializable]
#if EMBED
internal
#else
public
#endif
class LayoutCycleException : Exception
{
public LayoutCycleException()
: base("A cycle occurred while laying out the GUI.")
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
public LayoutCycleException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
public LayoutCycleException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
protected LayoutCycleException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
}