ExceptionExtensions.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using System.Net.Sockets;
  2. namespace MeloongCore.Extensions;
  3. public static class ExceptionExtensions {
  4. /// <summary>
  5. /// 返回该异常最底层的 <see cref="Exception.InnerException"/>。
  6. /// </summary>
  7. public static Exception RootException(this Exception ex) {
  8. while (ex.InnerException is { } inner) ex = inner;
  9. return ex;
  10. }
  11. /// <summary>
  12. /// 将异常所有的 <see cref="Exception.InnerException"/> 展开。
  13. /// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。
  14. /// </summary>
  15. public static IEnumerable<Exception> Flatten(this Exception ex) {
  16. var toFlatten = new Stack<Exception>();
  17. toFlatten.Push(ex);
  18. while (toFlatten.Any()) {
  19. var current = toFlatten.Pop();
  20. yield return current;
  21. if (current is AggregateException ag) {
  22. foreach (var inner in ag.InnerExceptions) toFlatten.Push(inner);
  23. } else if (current.InnerException is not null) {
  24. toFlatten.Push(current.InnerException);
  25. }
  26. }
  27. }
  28. /// <summary>
  29. /// 获取 <paramref name="ex"/> 的用户友好描述。
  30. /// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
  31. /// </summary>
  32. public static string GetDisplay(this Exception? ex, bool showMultilineStacks) {
  33. if (ex is null) return "无可用错误信息!";
  34. // 提取堆栈信息
  35. var lines = new List<string>();
  36. bool isInnerException = false;
  37. foreach (var currentEx in ex.Flatten()) {
  38. if (showMultilineStacks) {
  39. lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true));
  40. if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
  41. var stackLines = (currentEx.StackTrace?.ReplaceLineEndings("\r", true).Split('\r') ?? [])
  42. .Select(l => l.BeforeLast("(") + l.AfterLast(")"))
  43. .Distinct();
  44. lines.AddRange(stackLines);
  45. } else {
  46. lines.Add(currentEx.Message.ReplaceLineEndings(" ", true));
  47. }
  48. isInnerException = true;
  49. }
  50. // 分析常见错误原因
  51. string? commonReason = null;
  52. var rootException = ex.RootException();
  53. if (rootException is TypeLoadException or BadImageFormatException or MissingMethodException or NotImplementedException or TypeInitializationException)
  54. commonReason = "运行环境存在问题。请尝试重新安装 .NET Framework 4.8 然后再试。若无法安装,请先卸载较新版本的 .NET Framework,然后再尝试安装。";
  55. else if (rootException is UnauthorizedAccessException)
  56. commonReason = "程序权限不足。请尝试右键程序,选择以管理员身份运行,或将文件移动到其他文件夹。";
  57. else if (rootException is OutOfMemoryException)
  58. commonReason = "系统的运行内存不足。请在关闭一部分不需要的程序后再试。";
  59. else if (rootException is System.Net.Sockets.SocketException && lines.Any(l => l.Contains("WSAStartup")))
  60. commonReason = "请尝试卸载中国移动云盘,然后再试。";
  61. else if (ex.IsBadNetwork())
  62. commonReason = "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。";
  63. // 输出
  64. if (showMultilineStacks) {
  65. if (commonReason is null) {
  66. return lines.Join("\r\n");
  67. } else {
  68. return commonReason + "\r\n\r\n——————— 详细错误信息 ———————\r\n" + lines.Join("\r\n");
  69. }
  70. } else {
  71. lines = lines.Distinct().ToList();
  72. if (commonReason is null) {
  73. lines.Reverse();
  74. return lines.Join(" ← ");
  75. } else {
  76. return $"{commonReason}({lines.First()})";
  77. }
  78. }
  79. }
  80. /// <summary>
  81. /// 判断该异常是否是由于网络连接不良导致。
  82. /// </summary>
  83. public static bool IsBadNetwork(this Exception ex) {
  84. foreach (var currentEx in ex.Flatten()) {
  85. if (currentEx is TimeoutException) {
  86. return true;
  87. } else if (currentEx is TaskCanceledException) {
  88. return true;
  89. } else if (currentEx is HttpRequestCodeException reqEx) {
  90. if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false;
  91. if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true;
  92. } else if (currentEx is WebException webEx) {
  93. if (webEx.Response is HttpWebResponse response) {
  94. if (response.StatusCode is HttpStatusCode.Forbidden) return false;
  95. if (response.StatusCode is HttpStatusCode.RequestTimeout) return true;
  96. }
  97. if (webEx.Status is WebExceptionStatus.NameResolutionFailure or WebExceptionStatus.ConnectFailure or WebExceptionStatus.ReceiveFailure or
  98. WebExceptionStatus.SendFailure or WebExceptionStatus.ConnectionClosed or WebExceptionStatus.KeepAliveFailure or WebExceptionStatus.Timeout or
  99. WebExceptionStatus.ProxyNameResolutionFailure) return true;
  100. } else if (currentEx is SocketException socketEx) {
  101. if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or
  102. SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostDown or SocketError.HostUnreachable or
  103. SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData) return true;
  104. }
  105. }
  106. return false;
  107. }
  108. }