| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | |
| | | 5 | | namespace ProjectTemplate.Web.ErrorHandling; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Handles exceptions by generating and writing RFC 7807 Problem Details responses for HTTP requests when appropriate. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks>This exception handler inspects the HTTP context and exception to determine whether a Problem Details |
| | | 11 | | /// response should be written. It sets the response status code and includes trace information for diagnostics. In |
| | | 12 | | /// development environments, detailed exception messages are included in the response; in production, a generic error |
| | | 13 | | /// message is provided for server errors. The handler does not write a response if the request does not expect Problem |
| | | 14 | | /// Details or if the response has already started.</remarks> |
| | | 15 | | /// <param name="problemDetailsService">The service used to write Problem Details responses to the HTTP response.</param |
| | | 16 | | /// <param name="webHostEnvironment">The hosting environment used to determine whether to include detailed error informa |
| | | 17 | | /// <param name="logger">The logger used to record exception and error information.</param> |
| | 146 | 18 | | internal sealed class ProblemDetailsExceptionHandler( |
| | 146 | 19 | | IProblemDetailsService problemDetailsService, |
| | 146 | 20 | | IWebHostEnvironment webHostEnvironment, |
| | 146 | 21 | | ILogger<ProblemDetailsExceptionHandler> logger) : IExceptionHandler |
| | | 22 | | { |
| | | 23 | | /// <summary> |
| | | 24 | | /// Attempts to handle the specified exception by generating and writing a Problem Details response to the HTTP |
| | | 25 | | /// context asynchronously. |
| | | 26 | | /// </summary> |
| | | 27 | | /// <remarks>A Problem Details response is only written if the request is classified as requiring Problem |
| | | 28 | | /// Details and the response has not already started. If the response cannot be written, the method returns <see |
| | | 29 | | /// langword="false"/> and does not modify the response.</remarks> |
| | | 30 | | /// <param name="httpContext">The HTTP context for the current request. Cannot be null.</param> |
| | | 31 | | /// <param name="exception">The exception to handle and convert into a Problem Details response. Cannot be null.</pa |
| | | 32 | | /// <param name="cancellationToken">A token that can be used to cancel the asynchronous operation.</param> |
| | | 33 | | /// <returns>A task that represents the asynchronous operation. The task result contains <see langword="true"/> if a |
| | | 34 | | /// Details response was written; otherwise, <see langword="false"/>.</returns> |
| | | 35 | | public async ValueTask<bool> TryHandleAsync( |
| | | 36 | | HttpContext httpContext, |
| | | 37 | | Exception exception, |
| | | 38 | | CancellationToken cancellationToken) |
| | | 39 | | { |
| | 20 | 40 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | 20 | 41 | | ArgumentNullException.ThrowIfNull(exception); |
| | | 42 | | |
| | 20 | 43 | | if (!ProblemDetailsRequestClassifier.ShouldWriteProblemDetails(httpContext)) |
| | | 44 | | { |
| | 2 | 45 | | return false; |
| | | 46 | | } |
| | | 47 | | |
| | 18 | 48 | | if (httpContext.Response.HasStarted) |
| | | 49 | | { |
| | 2 | 50 | | return false; |
| | | 51 | | } |
| | | 52 | | |
| | 16 | 53 | | ProblemDetails problemDetails = CreateProblemDetails(httpContext, exception); |
| | | 54 | | |
| | 16 | 55 | | LogException(logger, exception, problemDetails.Status ?? StatusCodes.Status500InternalServerError, httpContext); |
| | | 56 | | |
| | 16 | 57 | | httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError; |
| | | 58 | | |
| | 16 | 59 | | var problemDetailsContext = new ProblemDetailsContext |
| | 16 | 60 | | { |
| | 16 | 61 | | HttpContext = httpContext, |
| | 16 | 62 | | ProblemDetails = problemDetails |
| | 16 | 63 | | }; |
| | | 64 | | |
| | 16 | 65 | | return await problemDetailsService.TryWriteAsync(problemDetailsContext); |
| | 20 | 66 | | } |
| | | 67 | | |
| | | 68 | | private ProblemDetails CreateProblemDetails(HttpContext httpContext, Exception exception) |
| | | 69 | | { |
| | 16 | 70 | | int statusCode = GetStatusCode(exception); |
| | 16 | 71 | | string title = GetTitle(statusCode); |
| | | 72 | | |
| | 16 | 73 | | var problemDetails = new ProblemDetails |
| | 16 | 74 | | { |
| | 16 | 75 | | Status = statusCode, |
| | 16 | 76 | | Title = title, |
| | 16 | 77 | | Type = $"https://httpstatuses.com/{statusCode}", |
| | 16 | 78 | | Instance = httpContext.Request.Path |
| | 16 | 79 | | }; |
| | | 80 | | |
| | 16 | 81 | | problemDetails.Extensions["traceId"] = Activity.Current?.Id ?? httpContext.TraceIdentifier; |
| | 16 | 82 | | problemDetails.Extensions["requestId"] = httpContext.TraceIdentifier; |
| | | 83 | | |
| | 16 | 84 | | if (webHostEnvironment.IsDevelopment()) |
| | | 85 | | { |
| | 2 | 86 | | problemDetails.Detail = exception.Message; |
| | | 87 | | } |
| | 14 | 88 | | else if (statusCode >= StatusCodes.Status500InternalServerError) |
| | | 89 | | { |
| | 6 | 90 | | problemDetails.Detail = "An unexpected error occurred. Contact support with the request ID."; |
| | | 91 | | } |
| | | 92 | | |
| | 16 | 93 | | return problemDetails; |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | private static int GetStatusCode(Exception exception) |
| | | 97 | | { |
| | 16 | 98 | | return exception switch |
| | 16 | 99 | | { |
| | 2 | 100 | | BadHttpRequestException => StatusCodes.Status400BadRequest, |
| | 6 | 101 | | ArgumentException => StatusCodes.Status400BadRequest, |
| | 2 | 102 | | UnauthorizedAccessException => StatusCodes.Status403Forbidden, |
| | 2 | 103 | | TimeoutException => StatusCodes.Status503ServiceUnavailable, |
| | 4 | 104 | | _ => StatusCodes.Status500InternalServerError |
| | 16 | 105 | | }; |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | private static string GetTitle(int statusCode) |
| | | 109 | | { |
| | 16 | 110 | | return statusCode switch |
| | 16 | 111 | | { |
| | 8 | 112 | | StatusCodes.Status400BadRequest => "Bad Request", |
| | 2 | 113 | | StatusCodes.Status403Forbidden => "Forbidden", |
| | 0 | 114 | | StatusCodes.Status404NotFound => "Not Found", |
| | 2 | 115 | | StatusCodes.Status503ServiceUnavailable => "Service Unavailable", |
| | 4 | 116 | | _ => "Internal Server Error" |
| | 16 | 117 | | }; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | private static void LogException( |
| | | 121 | | ILogger logger, |
| | | 122 | | Exception exception, |
| | | 123 | | int statusCode, |
| | | 124 | | HttpContext httpContext) |
| | | 125 | | { |
| | 16 | 126 | | if (statusCode >= StatusCodes.Status500InternalServerError) |
| | | 127 | | { |
| | 6 | 128 | | ProblemDetailsLogMessages.UnhandledException( |
| | 6 | 129 | | logger, |
| | 6 | 130 | | exception, |
| | 6 | 131 | | statusCode, |
| | 6 | 132 | | httpContext.TraceIdentifier, |
| | 6 | 133 | | httpContext.Request.Path); |
| | | 134 | | } |
| | | 135 | | else |
| | | 136 | | { |
| | 10 | 137 | | ProblemDetailsLogMessages.HandledException( |
| | 10 | 138 | | logger, |
| | 10 | 139 | | exception, |
| | 10 | 140 | | statusCode, |
| | 10 | 141 | | httpContext.TraceIdentifier, |
| | 10 | 142 | | httpContext.Request.Path); |
| | | 143 | | } |
| | 10 | 144 | | } |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Provides strongly-typed logging methods for recording events related to the conversion of exceptions to Problem |
| | | 149 | | /// Details responses. |
| | | 150 | | /// </summary> |
| | | 151 | | /// <remarks>This class defines logging message templates for use with the Microsoft.Extensions.Logging source |
| | | 152 | | /// generator. The methods are intended for internal use to standardize log output when exceptions are converted to |
| | | 153 | | /// Problem Details in HTTP responses.</remarks> |
| | | 154 | | internal static partial class ProblemDetailsLogMessages |
| | | 155 | | { |
| | | 156 | | /// <summary> |
| | | 157 | | /// Logs an unhandled exception as an error, including HTTP status code, request identifier, and request path |
| | | 158 | | /// information. |
| | | 159 | | /// </summary> |
| | | 160 | | /// <remarks>This method is intended for use in centralized exception handling scenarios to ensure |
| | | 161 | | /// consistent logging of unhandled exceptions with relevant request context.</remarks> |
| | | 162 | | /// <param name="logger">The logger used to write the error message.</param> |
| | | 163 | | /// <param name="exception">The exception that was not handled.</param> |
| | | 164 | | /// <param name="statusCode">The HTTP status code associated with the error response.</param> |
| | | 165 | | /// <param name="requestId">The unique identifier for the current request.</param> |
| | | 166 | | /// <param name="path">The request path where the exception occurred.</param> |
| | | 167 | | [LoggerMessage( |
| | | 168 | | EventId = 32001, |
| | | 169 | | Level = LogLevel.Error, |
| | | 170 | | Message = "Unhandled exception converted to Problem Details. StatusCode: {StatusCode}. RequestId: {RequestId}. P |
| | | 171 | | public static partial void UnhandledException( |
| | | 172 | | ILogger logger, |
| | | 173 | | Exception exception, |
| | | 174 | | int statusCode, |
| | | 175 | | string requestId, |
| | | 176 | | string path); |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Logs a warning message indicating that a handled exception was converted to a Problem Details response, |
| | | 180 | | /// including status code, request ID, and request path information. |
| | | 181 | | /// </summary> |
| | | 182 | | /// <remarks>This method is intended for use in exception handling middleware or filters to provide |
| | | 183 | | /// consistent logging of handled exceptions that result in Problem Details responses. The log entry includes |
| | | 184 | | /// contextual information to aid in troubleshooting.</remarks> |
| | | 185 | | /// <param name="logger">The logger used to write the warning message.</param> |
| | | 186 | | /// <param name="exception">The exception that was handled and converted to a Problem Details response.</param> |
| | | 187 | | /// <param name="statusCode">The HTTP status code associated with the Problem Details response.</param> |
| | | 188 | | /// <param name="requestId">The unique identifier for the request in which the exception occurred.</param> |
| | | 189 | | /// <param name="path">The request path where the exception was handled.</param> |
| | | 190 | | [LoggerMessage( |
| | | 191 | | EventId = 32002, |
| | | 192 | | Level = LogLevel.Warning, |
| | | 193 | | Message = "Handled exception converted to Problem Details. StatusCode: {StatusCode}. RequestId: {RequestId}. Pat |
| | | 194 | | public static partial void HandledException( |
| | | 195 | | ILogger logger, |
| | | 196 | | Exception exception, |
| | | 197 | | int statusCode, |
| | | 198 | | string requestId, |
| | | 199 | | string path); |
| | | 200 | | } |