-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexception-handler.cs
More file actions
executable file
·31 lines (23 loc) · 1.05 KB
/
exception-handler.cs
File metadata and controls
executable file
·31 lines (23 loc) · 1.05 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
// Program.cs
builder.Services.AddExceptionHandler<ApiValidationExceptionHandler>();
builder.Services.AddExceptionHandler<ApiExceptionHandler>();
app.UseExceptionHandler();
// ApiValidationExceptionHandler.cs
public class ApiValidationExceptionHandler(IHostEnvironment env) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
if (exception is ValidationException)
{
ValidationProblemDetails pd = new ValidationProblemDetails();
pd.Title = "Internal Server Error";
pd.Status = StatusCodes.Status400BadRequest;
pd.Detail = env.IsDevelopment() ? exception.Message : string.Empty;
pd.Extensions.Add("trace_Id", "XOXOOOX");
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
await httpContext.Response.WriteAsJsonAsync(pd);
return true; // konec pipeline
}
return false; // umožní propad do dalšího handleru
}
}