| | | 1 | | using AmbientServices.Utilities; |
| | | 2 | | using System; |
| | | 3 | | using System.Text; |
| | | 4 | | |
| | | 5 | | namespace AmbientServices.Extensions; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// A static class that extends <see cref="System.Exception"/>. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// <pitch>Log-friendly exception rendering: a compact exception string with irrelevant stack frames and machine-specifi |
| | | 12 | | /// <pledge>The filtered string renders the innermost exception first, each as a bracketed type name and message followe |
| | | 13 | | /// </remarks> |
| | | 14 | | public static class ExceptionExtensions |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Gets a filtered version of the exception string, with irrelevant stack frames and file paths stripped out. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="exception">The <see cref="Exception"/> for which we are to get a string.</param> |
| | | 20 | | /// <returns>A filtered string for the exception.</returns> |
| | | 21 | | public static string ToFilteredString(this Exception exception) |
| | | 22 | | { |
| | | 23 | | #if NET5_0_OR_GREATER |
| | 2 | 24 | | ArgumentNullException.ThrowIfNull(exception); |
| | | 25 | | #else |
| | | 26 | | if (exception is null) throw new ArgumentNullException(nameof(exception)); |
| | | 27 | | #endif |
| | 2 | 28 | | StringBuilder stack = new(); |
| | 2 | 29 | | ExceptionUtilities.BuildFilteredString(exception, stack); |
| | 2 | 30 | | return stack.ToString(); |
| | | 31 | | } |
| | | 32 | | /// <summary> |
| | | 33 | | /// Gets the type name for the exception, which is literally the type name with any trailing "Exception" r |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="e">The <see cref="Exception"/> whose type name is to be determined.</param> |
| | | 36 | | /// <returns>The type name for the exception.</returns> |
| | | 37 | | public static string TypeName(this Exception e) |
| | | 38 | | { |
| | | 39 | | #if NET5_0_OR_GREATER |
| | 2 | 40 | | ArgumentNullException.ThrowIfNull(e); |
| | | 41 | | #else |
| | | 42 | | if (e is null) throw new ArgumentNullException(nameof(e)); |
| | | 43 | | #endif |
| | 2 | 44 | | string typeName = e.GetType().Name; |
| | 2 | 45 | | return typeName.EndsWith("Exception", StringComparison.Ordinal) ? typeName.Substring(0, typeName.Length - 9) : t |
| | | 46 | | } |
| | | 47 | | } |