Skip to content

Commit 988c8e6

Browse files
committed
add Global exception handler
1 parent 114011d commit 988c8e6

File tree

4 files changed

+45
-47
lines changed

4 files changed

+45
-47
lines changed

JixMinApi/Features/Todo/TodoEndpoints.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ namespace JixMinApi.Features.Todo;
1010

1111
public static class TodoEndpoints
1212
{
13-
public static void InjectTodoEndpointServices(this IServiceCollection services)
13+
public static void AddTodoEndpointServices(this IServiceCollection services)
1414
{
1515
services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase(Constants.TodoApiGroupName));
1616
}
1717

18-
public static void MapTodoEndpoints(this WebApplication app)
18+
public static void UseTodoEndpoints(this WebApplication app)
1919
{
2020
var group = app.MapGroup(Constants.TodoApiRootPath)
2121
.WithOpenApi(x => new OpenApiOperation(x)

JixMinApi/Program.cs

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using JixMinApi.Features.Todo;
2+
using JixMinApi.Shared;
23
using Microsoft.OpenApi.Models;
34
using System.Reflection;
45

@@ -23,7 +24,10 @@
2324
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
2425

2526
// Inject endpoint services
26-
builder.Services.InjectTodoEndpointServices();
27+
builder.Services.AddTodoEndpointServices();
28+
29+
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
30+
builder.Services.AddProblemDetails();
2731

2832
var app = builder.Build();
2933

@@ -35,8 +39,7 @@
3539
}
3640

3741
app.UseHttpsRedirection();
38-
39-
// Map Endpoints
40-
app.MapTodoEndpoints();
42+
app.UseExceptionHandler();
43+
app.UseTodoEndpoints();
4144

4245
app.Run();
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using Microsoft.AspNetCore.Diagnostics;
2+
using Microsoft.AspNetCore.Mvc;
3+
4+
namespace JixMinApi.Shared;
5+
6+
internal sealed class GlobalExceptionHandler : IExceptionHandler
7+
{
8+
private readonly ILogger<GlobalExceptionHandler> _logger;
9+
10+
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
11+
{
12+
_logger = logger;
13+
}
14+
15+
public async ValueTask<bool> TryHandleAsync(
16+
HttpContext httpContext,
17+
Exception exception,
18+
CancellationToken cancellationToken)
19+
{
20+
_logger.LogError(
21+
exception, "Exception occurred: {Message}", exception.Message);
22+
23+
var problemDetails = new ProblemDetails
24+
{
25+
Status = StatusCodes.Status500InternalServerError,
26+
Title = "Server error"
27+
};
28+
29+
httpContext.Response.StatusCode = problemDetails.Status.Value;
30+
31+
await httpContext.Response
32+
.WriteAsJsonAsync(problemDetails, cancellationToken);
33+
34+
return true;
35+
}
36+
}

JixMinApi/Shared/Result.cs

-41
This file was deleted.

0 commit comments

Comments
 (0)