Skip to content

Commit

Permalink
add Global exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jicking committed Apr 18, 2024
1 parent 114011d commit 988c8e6
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 47 deletions.
4 changes: 2 additions & 2 deletions JixMinApi/Features/Todo/TodoEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ namespace JixMinApi.Features.Todo;

public static class TodoEndpoints
{
public static void InjectTodoEndpointServices(this IServiceCollection services)
public static void AddTodoEndpointServices(this IServiceCollection services)
{
services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase(Constants.TodoApiGroupName));
}

public static void MapTodoEndpoints(this WebApplication app)
public static void UseTodoEndpoints(this WebApplication app)
{
var group = app.MapGroup(Constants.TodoApiRootPath)
.WithOpenApi(x => new OpenApiOperation(x)
Expand Down
11 changes: 7 additions & 4 deletions JixMinApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using JixMinApi.Features.Todo;
using JixMinApi.Shared;
using Microsoft.OpenApi.Models;
using System.Reflection;

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

// Inject endpoint services
builder.Services.InjectTodoEndpointServices();
builder.Services.AddTodoEndpointServices();

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();

var app = builder.Build();

Expand All @@ -35,8 +39,7 @@
}

app.UseHttpsRedirection();

// Map Endpoints
app.MapTodoEndpoints();
app.UseExceptionHandler();
app.UseTodoEndpoints();

app.Run();
36 changes: 36 additions & 0 deletions JixMinApi/Shared/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace JixMinApi.Shared;

internal sealed class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;

public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}

public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(
exception, "Exception occurred: {Message}", exception.Message);

var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Server error"
};

httpContext.Response.StatusCode = problemDetails.Status.Value;

await httpContext.Response
.WriteAsJsonAsync(problemDetails, cancellationToken);

return true;
}
}
41 changes: 0 additions & 41 deletions JixMinApi/Shared/Result.cs

This file was deleted.

0 comments on commit 988c8e6

Please sign in to comment.