| | 1 | | // Copyright DotNet API Diff Project Contributors - SPDX Identifier: MIT |
| | 2 | | using System.Reflection; |
| | 3 | | using System.Security; |
| | 4 | | using DotNetApiDiff.Interfaces; |
| | 5 | | using Microsoft.Extensions.Logging; |
| | 6 | |
|
| | 7 | | namespace DotNetApiDiff.ExitCodes |
| | 8 | | { |
| | 9 | | /// <summary> |
| | 10 | | /// Provides centralized exception handling for the application. |
| | 11 | | /// </summary> |
| | 12 | | public class GlobalExceptionHandler : IGlobalExceptionHandler |
| | 13 | | { |
| | 14 | | private readonly ILogger<GlobalExceptionHandler> _logger; |
| | 15 | | private readonly IExitCodeManager _exitCodeManager; |
| | 16 | |
|
| | 17 | | /// <summary> |
| | 18 | | /// Initializes a new instance of the <see cref="GlobalExceptionHandler"/> class. |
| | 19 | | /// </summary> |
| | 20 | | /// <param name="logger">The logger to use for logging exceptions.</param> |
| | 21 | | /// <param name="exitCodeManager">The exit code manager to determine appropriate exit codes.</param> |
| 18 | 22 | | public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger, IExitCodeManager exitCodeManager) |
| 18 | 23 | | { |
| 18 | 24 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 18 | 25 | | _exitCodeManager = exitCodeManager ?? throw new ArgumentNullException(nameof(exitCodeManager)); |
| 18 | 26 | | } |
| | 27 | |
|
| | 28 | | /// <summary> |
| | 29 | | /// Handles an exception by logging it and determining the appropriate exit code. |
| | 30 | | /// </summary> |
| | 31 | | /// <param name="exception">The exception to handle.</param> |
| | 32 | | /// <param name="context">Optional context information about where the exception occurred.</param> |
| | 33 | | /// <returns>The appropriate exit code for the exception.</returns> |
| | 34 | | public int HandleException(Exception exception, string? context = null) |
| 8 | 35 | | { |
| 8 | 36 | | if (exception == null) |
| 1 | 37 | | { |
| 1 | 38 | | _logger.LogError("HandleException called with null exception"); |
| 1 | 39 | | return _exitCodeManager.GetExitCodeForException(new ArgumentNullException(nameof(exception))); |
| | 40 | | } |
| | 41 | |
|
| | 42 | | // Log the exception with context if provided |
| 7 | 43 | | if (!string.IsNullOrEmpty(context)) |
| 4 | 44 | | { |
| 4 | 45 | | _logger.LogError(exception, "Error in {Context}: {Message}", context, exception.Message); |
| 4 | 46 | | } |
| | 47 | | else |
| 3 | 48 | | { |
| 3 | 49 | | _logger.LogError(exception, "Error: {Message}", exception.Message); |
| 3 | 50 | | } |
| | 51 | |
|
| | 52 | | // Log additional details for specific exception types |
| 7 | 53 | | LogExceptionDetails(exception); |
| | 54 | |
|
| | 55 | | // Determine the appropriate exit code |
| 7 | 56 | | int exitCode = _exitCodeManager.GetExitCodeForException(exception); |
| | 57 | |
|
| 7 | 58 | | _logger.LogInformation( |
| 7 | 59 | | "Exiting with code {ExitCode}: {Description}", |
| 7 | 60 | | exitCode, |
| 7 | 61 | | _exitCodeManager.GetExitCodeDescription(exitCode)); |
| | 62 | |
|
| 7 | 63 | | return exitCode; |
| 8 | 64 | | } |
| | 65 | |
|
| | 66 | | /// <summary> |
| | 67 | | /// Logs additional details for specific exception types. |
| | 68 | | /// </summary> |
| | 69 | | /// <param name="exception">The exception to log details for.</param> |
| | 70 | | private void LogExceptionDetails(Exception exception) |
| 7 | 71 | | { |
| 7 | 72 | | switch (exception) |
| | 73 | | { |
| | 74 | | case ReflectionTypeLoadException typeLoadEx: |
| 1 | 75 | | LogReflectionTypeLoadException(typeLoadEx); |
| 1 | 76 | | break; |
| | 77 | | case AggregateException aggregateEx: |
| 1 | 78 | | LogAggregateException(aggregateEx); |
| 1 | 79 | | break; |
| | 80 | | case FileNotFoundException fileNotFoundEx: |
| 1 | 81 | | _logger.LogError("File not found: {FileName}", fileNotFoundEx.FileName); |
| 1 | 82 | | break; |
| | 83 | | case BadImageFormatException badImageEx: |
| 0 | 84 | | _logger.LogError("Bad image format: {FileName}", badImageEx.FileName); |
| 0 | 85 | | break; |
| | 86 | | case SecurityException securityEx: |
| 0 | 87 | | _logger.LogError("Security exception: {PermissionType}", securityEx.PermissionType); |
| 0 | 88 | | break; |
| | 89 | | case InvalidOperationException: |
| | 90 | | // Log the stack trace for InvalidOperationException to help diagnose the issue |
| 1 | 91 | | _logger.LogDebug("Stack trace: {StackTrace}", exception.StackTrace); |
| 1 | 92 | | break; |
| | 93 | | } |
| | 94 | |
|
| | 95 | | // Log inner exception if present |
| 7 | 96 | | if (exception.InnerException != null) |
| 1 | 97 | | { |
| 1 | 98 | | _logger.LogDebug("Inner exception: {Message}", exception.InnerException.Message); |
| 1 | 99 | | } |
| 7 | 100 | | } |
| | 101 | |
|
| | 102 | | /// <summary> |
| | 103 | | /// Logs details for a ReflectionTypeLoadException. |
| | 104 | | /// </summary> |
| | 105 | | /// <param name="exception">The ReflectionTypeLoadException to log details for.</param> |
| | 106 | | private void LogReflectionTypeLoadException(ReflectionTypeLoadException exception) |
| 1 | 107 | | { |
| 1 | 108 | | _logger.LogError("ReflectionTypeLoadException: Failed to load {Count} types", exception.Types?.Length ?? 0); |
| | 109 | |
|
| 1 | 110 | | if (exception.LoaderExceptions != null) |
| 1 | 111 | | { |
| 1 | 112 | | int loaderExceptionCount = exception.LoaderExceptions.Length; |
| 1 | 113 | | _logger.LogError("Loader exceptions count: {Count}", loaderExceptionCount); |
| | 114 | |
|
| | 115 | | // Log up to 5 loader exceptions to avoid excessive logging |
| 1 | 116 | | int logCount = Math.Min(loaderExceptionCount, 5); |
| 6 | 117 | | for (int i = 0; i < logCount; i++) |
| 2 | 118 | | { |
| 2 | 119 | | var loaderEx = exception.LoaderExceptions[i]; |
| 2 | 120 | | if (loaderEx != null) |
| 2 | 121 | | { |
| 2 | 122 | | _logger.LogError(loaderEx, "Loader exception {Index}: {Message}", i + 1, loaderEx.Message); |
| 2 | 123 | | } |
| 2 | 124 | | } |
| | 125 | |
|
| 1 | 126 | | if (loaderExceptionCount > logCount) |
| 0 | 127 | | { |
| 0 | 128 | | _logger.LogError("... and {Count} more loader exceptions", loaderExceptionCount - logCount); |
| 0 | 129 | | } |
| 1 | 130 | | } |
| 1 | 131 | | } |
| | 132 | |
|
| | 133 | | /// <summary> |
| | 134 | | /// Logs details for an AggregateException. |
| | 135 | | /// </summary> |
| | 136 | | /// <param name="exception">The AggregateException to log details for.</param> |
| | 137 | | private void LogAggregateException(AggregateException exception) |
| 1 | 138 | | { |
| 1 | 139 | | _logger.LogError("AggregateException with {Count} inner exceptions", exception.InnerExceptions.Count); |
| | 140 | |
|
| | 141 | | // Log up to 5 inner exceptions to avoid excessive logging |
| 1 | 142 | | int logCount = Math.Min(exception.InnerExceptions.Count, 5); |
| 6 | 143 | | for (int i = 0; i < logCount; i++) |
| 2 | 144 | | { |
| 2 | 145 | | var innerEx = exception.InnerExceptions[i]; |
| 2 | 146 | | _logger.LogError(innerEx, "Inner exception {Index}: {Message}", i + 1, innerEx.Message); |
| 2 | 147 | | } |
| | 148 | |
|
| 1 | 149 | | if (exception.InnerExceptions.Count > logCount) |
| 0 | 150 | | { |
| 0 | 151 | | _logger.LogError("... and {Count} more inner exceptions", exception.InnerExceptions.Count - logCount); |
| 0 | 152 | | } |
| 1 | 153 | | } |
| | 154 | |
|
| | 155 | | /// <summary> |
| | 156 | | /// Sets up global unhandled exception handling. |
| | 157 | | /// </summary> |
| | 158 | | public void SetupGlobalExceptionHandling() |
| 9 | 159 | | { |
| | 160 | | // Handle unhandled exceptions in the current AppDomain |
| 9 | 161 | | AppDomain.CurrentDomain.UnhandledException += (sender, e) => |
| 0 | 162 | | { |
| 0 | 163 | | if (e.ExceptionObject is Exception ex) |
| 0 | 164 | | { |
| 0 | 165 | | _logger.LogCritical(ex, "Unhandled exception in AppDomain: {Message}", ex.Message); |
| 0 | 166 | | } |
| 9 | 167 | | else |
| 0 | 168 | | { |
| 0 | 169 | | _logger.LogCritical("Unhandled non-exception object in AppDomain: {Object}", e.ExceptionObject); |
| 0 | 170 | | } |
| 9 | 171 | | }; |
| | 172 | |
|
| | 173 | | // Handle unhandled exceptions in tasks |
| 9 | 174 | | TaskScheduler.UnobservedTaskException += (sender, e) => |
| 0 | 175 | | { |
| 0 | 176 | | _logger.LogCritical(e.Exception, "Unobserved task exception: {Message}", e.Exception.Message); |
| 0 | 177 | | e.SetObserved(); // Mark as observed to prevent process termination |
| 9 | 178 | | }; |
| | 179 | |
|
| | 180 | | // Handle first-chance exceptions (useful for debugging) |
| 9 | 181 | | if (_logger.IsEnabled(LogLevel.Debug)) |
| 0 | 182 | | { |
| | 183 | | // Register for FirstChanceException events only when debug logging is enabled |
| 0 | 184 | | AppDomain.CurrentDomain.FirstChanceException += (sender, e) => |
| 0 | 185 | | { |
| 0 | 186 | | // Only log first-chance exceptions at debug level to avoid noise |
| 0 | 187 | | _logger.LogDebug(e.Exception, "First chance exception: {Message}", e.Exception.Message); |
| 0 | 188 | | }; |
| 0 | 189 | | } |
| 9 | 190 | | } |
| | 191 | | } |
| | 192 | | } |