ExceptionExtensions.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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="multiline"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
  31. /// </summary>
  32. public static string GetDisplay(this Exception? ex, bool multiline) {
  33. if (ex is null) return "无可用错误信息!";
  34. // 提取堆栈信息
  35. var lines = new List<string>();
  36. bool isInnerException = false;
  37. static string getExceptionMessage(Exception e) => e.Message + (e switch {
  38. WebException webEx => $" (Status={webEx.Status})",
  39. SocketException socketEx => $" (SocketErrorCode={socketEx.SocketErrorCode})",
  40. _ => ""
  41. });
  42. foreach (var currentEx in ex.Flatten()) {
  43. if (multiline) {
  44. lines.Add((isInnerException ? "→ " : "") + getExceptionMessage(currentEx).ReplaceLineEndings("\r\n", true));
  45. var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? [])
  46. .Select(l => l.BeforeLast("(") + l.AfterLast(")"))
  47. .Distinct();
  48. lines.AddRange(stackLines);
  49. if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
  50. } else {
  51. lines.Add(getExceptionMessage(currentEx).ReplaceLineEndings(" ", true));
  52. }
  53. isInnerException = true;
  54. }
  55. // 分析常见错误原因
  56. string? commonReason = null;
  57. var rootException = ex.RootException();
  58. if (rootException is TypeLoadException or BadImageFormatException or MissingMethodException or NotImplementedException or TypeInitializationException)
  59. commonReason = "运行环境存在问题。请尝试重新安装 .NET Framework 4.8 然后再试。若无法安装,请先卸载较新版本的 .NET Framework,然后再尝试安装。";
  60. else if (rootException is UnauthorizedAccessException)
  61. commonReason = "程序权限不足。请尝试右键程序,选择以管理员身份运行,或将文件移动到其他文件夹。";
  62. else if (rootException is OutOfMemoryException)
  63. commonReason = "系统的运行内存不足。请在关闭一部分不需要的程序后再试。";
  64. else if (rootException is System.Net.Sockets.SocketException && lines.Any(l => l.Contains("WSAStartup")))
  65. commonReason = "请尝试卸载中国移动云盘,然后再试。";
  66. else if (ex.IsBadNetwork())
  67. commonReason = "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。";
  68. // 输出
  69. if (multiline) {
  70. if (commonReason is null) {
  71. return lines.Join("\r\n");
  72. } else {
  73. return commonReason + "\r\n\r\n——————— 详细错误信息 ———————\r\n" + lines.Join("\r\n");
  74. }
  75. } else {
  76. lines = lines.Distinct().ToList();
  77. if (commonReason is null) {
  78. lines.Reverse();
  79. return lines.Join(" ← ");
  80. } else {
  81. return $"{commonReason}({lines.First()})";
  82. }
  83. }
  84. }
  85. /// <summary>
  86. /// 判断该异常是否是由于网络连接不良导致。
  87. /// </summary>
  88. public static bool IsBadNetwork(this Exception ex) {
  89. foreach (var currentEx in ex.Flatten()) {
  90. if (currentEx is TimeoutException) {
  91. return true;
  92. } else if (currentEx is TaskCanceledException) {
  93. return true;
  94. } else if (currentEx is HttpRequestCodeException reqEx) {
  95. if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false;
  96. if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true;
  97. } else if (currentEx is WebException webEx) {
  98. if (webEx.Response is HttpWebResponse response) {
  99. if (response.StatusCode is HttpStatusCode.Forbidden) return false;
  100. if (response.StatusCode is HttpStatusCode.RequestTimeout) return true;
  101. }
  102. if (webEx.Status is WebExceptionStatus.NameResolutionFailure or WebExceptionStatus.ConnectFailure or WebExceptionStatus.ReceiveFailure or
  103. WebExceptionStatus.SendFailure or WebExceptionStatus.ConnectionClosed or WebExceptionStatus.KeepAliveFailure or WebExceptionStatus.Timeout or
  104. WebExceptionStatus.ProxyNameResolutionFailure or WebExceptionStatus.SecureChannelFailure) return true;
  105. } else if (currentEx is SocketException socketEx) {
  106. if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or
  107. SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or
  108. SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData) return true;
  109. }
  110. }
  111. return false;
  112. }
  113. }