-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
61 additions
and
45 deletions.
There are no files selected for viewing
This file contains 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,48 @@ | ||
using System.Diagnostics; | ||
using Microsoft.AspNetCore.Diagnostics; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace JixMinApi.Shared; | ||
|
||
|
||
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler | ||
{ | ||
private readonly ILogger<GlobalExceptionHandler> logger = logger; | ||
|
||
public async ValueTask<bool> TryHandleAsync( | ||
HttpContext httpContext, | ||
Exception exception, | ||
CancellationToken cancellationToken) | ||
{ | ||
var traceId = Activity.Current?.Id ?? httpContext.TraceIdentifier; | ||
|
||
logger.LogError( | ||
exception, | ||
"Could not process a request on machine {MachineName}. TraceId: {TraceId}", | ||
Environment.MachineName, | ||
traceId | ||
); | ||
|
||
var (statusCode, title) = MapException(exception); | ||
|
||
await Results.Problem( | ||
title: title, | ||
statusCode: statusCode, | ||
extensions: new Dictionary<string, object?> | ||
{ | ||
{"traceId", traceId} | ||
} | ||
).ExecuteAsync(httpContext); | ||
|
||
return true; | ||
} | ||
|
||
private static (int StatusCode, string Title) MapException(Exception exception) | ||
{ | ||
return exception switch | ||
{ | ||
ArgumentOutOfRangeException => (StatusCodes.Status400BadRequest, exception.Message), | ||
_ => (StatusCodes.Status500InternalServerError, "Server error") | ||
}; | ||
} | ||
} |
This file contains 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 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 was deleted.
Oops, something went wrong.