MCPcopy Create free account
hub / github.com/TryCatchLearn/Restore-v2 / ExceptionMiddleware

Class ExceptionMiddleware

API/Middleware/ExceptionMiddleware.cs:8–45  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6namespace API.Middleware;
7
8public class ExceptionMiddleware(IHostEnvironment env, ILogger<ExceptionMiddleware> logger)
9 : IMiddleware
10{
11 public async Task InvokeAsync(HttpContext context, RequestDelegate next)
12 {
13 try
14 {
15 await next(context);
16 }
17 catch (Exception ex)
18 {
19 await HandleException(context, ex);
20 }
21 }
22
23 private async Task HandleException(HttpContext context, Exception ex)
24 {
25 logger.LogError(ex, ex.Message);
26 context.Response.ContentType = "application/json";
27 context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
28
29 var response = new ProblemDetails
30 {
31 Status = 500,
32 Detail = env.IsDevelopment()
33 ? ex.StackTrace?.ToString()
34 : null,
35 Title = ex.Message
36 };
37
38 var options = new JsonSerializerOptions
39 {PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
40
41 var json = JsonSerializer.Serialize(response, options);
42
43 await context.Response.WriteAsync(json);
44 }
45}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected