Exception.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Runtime.Serialization;
  7. namespace System
  8. {
  9. [Serializable]
  10. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  11. public partial class Exception : ISerializable
  12. {
  13. private protected const string InnerExceptionPrefix = " ---> ";
  14. public Exception()
  15. {
  16. _HResult = HResults.COR_E_EXCEPTION;
  17. }
  18. public Exception(string? message)
  19. : this()
  20. {
  21. _message = message;
  22. }
  23. // Creates a new Exception. All derived classes should
  24. // provide this constructor.
  25. // Note: the stack trace is not started until the exception
  26. // is thrown
  27. //
  28. public Exception(string? message, Exception? innerException)
  29. : this()
  30. {
  31. _message = message;
  32. _innerException = innerException;
  33. }
  34. protected Exception(SerializationInfo info, StreamingContext context)
  35. {
  36. if (info == null)
  37. throw new ArgumentNullException(nameof(info));
  38. _message = info.GetString("Message"); // Do not rename (binary serialization)
  39. _data = (IDictionary?)(info.GetValueNoThrow("Data", typeof(IDictionary))); // Do not rename (binary serialization)
  40. _innerException = (Exception?)(info.GetValue("InnerException", typeof(Exception))); // Do not rename (binary serialization)
  41. _helpURL = info.GetString("HelpURL"); // Do not rename (binary serialization)
  42. _stackTraceString = info.GetString("StackTraceString"); // Do not rename (binary serialization)
  43. _HResult = info.GetInt32("HResult"); // Do not rename (binary serialization)
  44. _source = info.GetString("Source"); // Do not rename (binary serialization)
  45. RestoreRemoteStackTrace(info, context);
  46. }
  47. public virtual string Message => _message ?? SR.Format(SR.Exception_WasThrown, GetClassName());
  48. public virtual IDictionary Data => _data ??= CreateDataContainer();
  49. private string GetClassName() => GetType().ToString();
  50. // Retrieves the lowest exception (inner most) for the given Exception.
  51. // This will traverse exceptions using the innerException property.
  52. public virtual Exception GetBaseException()
  53. {
  54. Exception? inner = InnerException;
  55. Exception back = this;
  56. while (inner != null)
  57. {
  58. back = inner;
  59. inner = inner.InnerException;
  60. }
  61. return back;
  62. }
  63. public Exception? InnerException => _innerException;
  64. // Sets the help link for this exception.
  65. // This should be in a URL/URN form, such as:
  66. // "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
  67. public virtual string? HelpLink
  68. {
  69. get => _helpURL;
  70. set => _helpURL = value;
  71. }
  72. public virtual string? Source
  73. {
  74. get => _source ??= CreateSourceName();
  75. set => _source = value;
  76. }
  77. public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  78. {
  79. if (info == null)
  80. {
  81. throw new ArgumentNullException(nameof(info));
  82. }
  83. if (_source == null)
  84. {
  85. _source = Source; // Set the Source information correctly before serialization
  86. }
  87. info.AddValue("ClassName", GetClassName(), typeof(string)); // Do not rename (binary serialization)
  88. info.AddValue("Message", _message, typeof(string)); // Do not rename (binary serialization)
  89. info.AddValue("Data", _data, typeof(IDictionary)); // Do not rename (binary serialization)
  90. info.AddValue("InnerException", _innerException, typeof(Exception)); // Do not rename (binary serialization)
  91. info.AddValue("HelpURL", _helpURL, typeof(string)); // Do not rename (binary serialization)
  92. info.AddValue("StackTraceString", SerializationStackTraceString, typeof(string)); // Do not rename (binary serialization)
  93. info.AddValue("RemoteStackTraceString", SerializationRemoteStackTraceString, typeof(string)); // Do not rename (binary serialization)
  94. info.AddValue("RemoteStackIndex", 0, typeof(int)); // Do not rename (binary serialization)
  95. info.AddValue("ExceptionMethod", null, typeof(string)); // Do not rename (binary serialization)
  96. info.AddValue("HResult", _HResult); // Do not rename (binary serialization)
  97. info.AddValue("Source", _source, typeof(string)); // Do not rename (binary serialization)
  98. info.AddValue("WatsonBuckets", SerializationWatsonBuckets, typeof(byte[])); // Do not rename (binary serialization)
  99. }
  100. public override string ToString()
  101. {
  102. string className = GetClassName();
  103. string? message = Message;
  104. string innerExceptionString = _innerException?.ToString() ?? "";
  105. string endOfInnerExceptionResource = SR.Exception_EndOfInnerExceptionStack;
  106. string? stackTrace = StackTrace;
  107. // Calculate result string length
  108. int length = className.Length;
  109. checked
  110. {
  111. if (!string.IsNullOrEmpty(message))
  112. {
  113. length += 2 + message.Length;
  114. }
  115. if (_innerException != null)
  116. {
  117. length += Environment.NewLineConst.Length + InnerExceptionPrefix.Length + innerExceptionString.Length + Environment.NewLineConst.Length + 3 + endOfInnerExceptionResource.Length;
  118. }
  119. if (stackTrace != null)
  120. {
  121. length += Environment.NewLineConst.Length + stackTrace.Length;
  122. }
  123. }
  124. // Create the string
  125. string result = string.FastAllocateString(length);
  126. Span<char> resultSpan = new Span<char>(ref result.GetRawStringData(), result.Length);
  127. // Fill it in
  128. Write(className, ref resultSpan);
  129. if (!string.IsNullOrEmpty(message))
  130. {
  131. Write(": ", ref resultSpan);
  132. Write(message, ref resultSpan);
  133. }
  134. if (_innerException != null)
  135. {
  136. Write(Environment.NewLineConst, ref resultSpan);
  137. Write(InnerExceptionPrefix, ref resultSpan);
  138. Write(innerExceptionString, ref resultSpan);
  139. Write(Environment.NewLineConst, ref resultSpan);
  140. Write(" ", ref resultSpan);
  141. Write(endOfInnerExceptionResource, ref resultSpan);
  142. }
  143. if (stackTrace != null)
  144. {
  145. Write(Environment.NewLineConst, ref resultSpan);
  146. Write(stackTrace, ref resultSpan);
  147. }
  148. Debug.Assert(resultSpan.Length == 0);
  149. // Return it
  150. return result;
  151. static void Write(string source, ref Span<char> dest)
  152. {
  153. source.AsSpan().CopyTo(dest);
  154. dest = dest.Slice(source.Length);
  155. }
  156. }
  157. protected event EventHandler<SafeSerializationEventArgs>? SerializeObjectState
  158. {
  159. add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
  160. remove { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
  161. }
  162. public int HResult
  163. {
  164. get => _HResult;
  165. set => _HResult = value;
  166. }
  167. // this method is required so Object.GetType is not made virtual by the compiler
  168. // _Exception.GetType()
  169. public new Type GetType() => base.GetType();
  170. partial void RestoreRemoteStackTrace(SerializationInfo info, StreamingContext context);
  171. }
  172. }