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 27ad8f5
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 43 deletions.
2 changes: 1 addition & 1 deletion JixMinApi/Features/Todo/TodoEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ 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));
}
Expand Down
8 changes: 7 additions & 1 deletion 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,11 +24,16 @@
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();

// Configure the HTTP request pipeline.
app.UseExceptionHandler();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
Expand Down
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 27ad8f5

Please sign in to comment.