-
Notifications
You must be signed in to change notification settings - Fork 15
feat: add global exception handling middleware with RFC 7807 support #321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
src/Dotnet.Samples.AspNetCore.WebApi/Extensions/MiddlewareExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| using Dotnet.Samples.AspNetCore.WebApi.Middlewares; | ||
|
|
||
| namespace Dotnet.Samples.AspNetCore.WebApi.Extensions; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for configuring middleware in the application pipeline. | ||
| /// </summary> | ||
| public static class MiddlewareExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds global exception handling middleware to the application pipeline. | ||
| /// This middleware catches unhandled exceptions and returns RFC 7807 compliant error responses. | ||
| /// </summary> | ||
| /// <param name="app">The web application used to configure the HTTP pipeline, and routes.</param> | ||
| /// <returns>The WebApplication object for method chaining.</returns> | ||
| public static WebApplication UseExceptionHandling(this WebApplication app) | ||
| { | ||
| app.UseMiddleware<ExceptionMiddleware>(); | ||
| return app; | ||
| } | ||
| } |
117 changes: 117 additions & 0 deletions
117
src/Dotnet.Samples.AspNetCore.WebApi/Middlewares/ExceptionMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| using System.Text.Json; | ||
| using FluentValidation; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.EntityFrameworkCore; | ||
|
|
||
| namespace Dotnet.Samples.AspNetCore.WebApi.Middlewares; | ||
|
|
||
| /// <summary> | ||
| /// Middleware for global exception handling with RFC 7807 Problem Details format. | ||
| /// </summary> | ||
| public class ExceptionMiddleware(ILogger<ExceptionMiddleware> logger, IHostEnvironment environment) | ||
| { | ||
| private const string ProblemDetailsContentType = "application/problem+json"; | ||
|
|
||
| private static readonly JsonSerializerOptions JsonOptions = | ||
| new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; | ||
|
|
||
| /// <summary> | ||
| /// Invokes the middleware to handle exceptions globally. | ||
| /// </summary> | ||
| public async Task InvokeAsync(HttpContext context, RequestDelegate next) | ||
| { | ||
| try | ||
| { | ||
| await next(context); | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| await HandleExceptionAsync(context, exception); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Handles the exception and returns an RFC 7807 compliant error response. | ||
| /// </summary> | ||
| private async Task HandleExceptionAsync(HttpContext context, Exception exception) | ||
| { | ||
| var (status, title) = MapExceptionToStatusCode(exception); | ||
|
|
||
| var problemDetails = new ProblemDetails | ||
| { | ||
| Type = $"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{status}", | ||
| Title = title, | ||
| Status = status, | ||
| Detail = GetExceptionDetail(exception), | ||
| Instance = context.Request.Path | ||
| }; | ||
|
|
||
| // Add trace ID for request correlation | ||
| problemDetails.Extensions["traceId"] = context.TraceIdentifier; | ||
|
|
||
| // codeql[cs/log-forging] Serilog structured logging automatically escapes control characters | ||
| logger.LogError( | ||
| exception, | ||
| "Unhandled exception occurred. TraceId: {TraceId}, Path: {Path}, StatusCode: {StatusCode}", | ||
| context.TraceIdentifier, | ||
| context.Request.Path, | ||
| status | ||
| ); | ||
|
|
||
| // Only modify response if headers haven't been sent yet | ||
| if (!context.Response.HasStarted) | ||
| { | ||
| context.Response.StatusCode = status; | ||
| context.Response.ContentType = ProblemDetailsContentType; | ||
|
|
||
| await context.Response.WriteAsync( | ||
| JsonSerializer.Serialize(problemDetails, JsonOptions) | ||
| ); | ||
| } | ||
| else | ||
| { | ||
| logger.LogWarning( | ||
| "Unable to write error response for TraceId: {TraceId}. Response has already started.", | ||
| context.TraceIdentifier | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Maps exception types to appropriate HTTP status codes and titles. | ||
| /// </summary> | ||
| private static (int StatusCode, string Title) MapExceptionToStatusCode(Exception exception) | ||
| { | ||
| return exception switch | ||
| { | ||
| ValidationException => (StatusCodes.Status400BadRequest, "Validation Error"), | ||
| ArgumentException | ||
| or ArgumentNullException | ||
| => (StatusCodes.Status400BadRequest, "Bad Request"), | ||
| InvalidOperationException => (StatusCodes.Status400BadRequest, "Invalid Operation"), | ||
| DbUpdateConcurrencyException => (StatusCodes.Status409Conflict, "Concurrency Conflict"), | ||
| OperationCanceledException => (StatusCodes.Status408RequestTimeout, "Request Timeout"), | ||
| _ => (StatusCodes.Status500InternalServerError, "Internal Server Error") | ||
| }; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the exception detail based on the environment. | ||
| /// In Development: includes full exception details and stack trace. | ||
| /// In Production: returns a generic message without sensitive information. | ||
| /// </summary> | ||
| private string GetExceptionDetail(Exception exception) | ||
| { | ||
| if (environment.IsDevelopment()) | ||
| { | ||
| return $"{exception.Message}\n\nStack Trace:\n{exception.StackTrace}"; | ||
| } | ||
|
|
||
| return exception switch | ||
| { | ||
| ValidationException => exception.Message, | ||
| ArgumentException => exception.Message, | ||
| _ => "An unexpected error occurred while processing your request." | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.