Repository navigation
Expand file tree
/
Copy pathProblemDetailsExceptionHandler.cs
More file actions
82 lines (75 loc) · 3.03 KB
/
Copy pathProblemDetailsExceptionHandler.cs
File metadata and controls
82 lines (75 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
namespace CleanApiStarter.AspNetCoreDefaults;
public sealed class ProblemDetailsExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<ProblemDetailsExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is OperationCanceledException && httpContext.RequestAborted.IsCancellationRequested)
{
logger.LogDebug(
"Request {RequestMethod} {RequestPath} was canceled by the client",
httpContext.Request.Method,
httpContext.Request.Path);
// 499 Client Closed Request (nginx convention); no body since the client is gone.
httpContext.Response.StatusCode = 499;
return true;
}
(int statusCode, ProblemDetails problemDetails) = exception switch
{
BadHttpRequestException badRequestException => (
StatusCodes.Status400BadRequest,
new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Bad Request",
Type = "https://tools.ietf.org/html/rfc9110#section-15.5.1",
Detail = badRequestException.Message
}),
UnauthorizedAccessException => (
StatusCodes.Status401Unauthorized,
new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Type = "https://tools.ietf.org/html/rfc9110#section-15.5.2"
}),
_ => (
StatusCodes.Status500InternalServerError,
new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Internal Server Error",
Type = "https://tools.ietf.org/html/rfc9110#section-15.6.1",
Detail = "An unexpected error occurred."
})
};
if (statusCode >= StatusCodes.Status500InternalServerError)
{
logger.LogError(
exception,
"Unhandled exception while processing {RequestMethod} {RequestPath}",
httpContext.Request.Method,
httpContext.Request.Path);
}
else
{
logger.LogWarning(
exception,
"Handled exception with status {StatusCode} while processing {RequestMethod} {RequestPath}",
statusCode,
httpContext.Request.Method,
httpContext.Request.Path);
}
httpContext.Response.StatusCode = statusCode;
return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = problemDetails,
Exception = exception
});
}
}