Skip to content

Commit 27ad8f5

Browse files
committed
add Global exception handler
1 parent 114011d commit 27ad8f5

File tree

4 files changed

+44
-43
lines changed

4 files changed

+44
-43
lines changed

JixMinApi/Features/Todo/TodoEndpoints.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ 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
}

JixMinApi/Program.cs

+7-1
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,11 +24,16 @@
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

3034
// Configure the HTTP request pipeline.
35+
app.UseExceptionHandler();
36+
3137
if (app.Environment.IsDevelopment())
3238
{
3339
app.UseSwagger();
+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)