-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathBuilder.ErrorHandling.cs
44 lines (40 loc) · 1.54 KB
/
Builder.ErrorHandling.cs
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
using Microsoft.AspNetCore.Diagnostics;
public static partial class ApiBuilder
{
public static IServiceCollection AddErrorHandling(this IServiceCollection services)
{
services.AddExceptionHandler<ExceptionHandler>();
services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Instance = $"{context.HttpContext.Request.Method} {context.HttpContext.Request.Path}";
context.ProblemDetails.Extensions.TryAdd("requestId", context.HttpContext.TraceIdentifier);
};
});
return services;
}
}
public class ExceptionHandler(IProblemDetailsService problemDetailsService) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
var statusCode = exception switch
{
InvalidOperationException or ArgumentException => StatusCodes.Status422UnprocessableEntity,
BadHttpRequestException or FormatException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};
httpContext.Response.StatusCode = statusCode;
return await problemDetailsService.TryWriteAsync(new()
{
Exception = exception,
HttpContext = httpContext,
ProblemDetails = new()
{
Status = statusCode,
Detail = exception.Message
}
});
}
}