Skip to content

Commit

Permalink
update global exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jicking committed May 4, 2024
1 parent 6f08374 commit 2025980
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 45 deletions.
48 changes: 48 additions & 0 deletions JixMinApi/Common/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace JixMinApi.Shared;


public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> logger = logger;

public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var traceId = Activity.Current?.Id ?? httpContext.TraceIdentifier;

logger.LogError(
exception,
"Could not process a request on machine {MachineName}. TraceId: {TraceId}",
Environment.MachineName,
traceId
);

var (statusCode, title) = MapException(exception);

await Results.Problem(
title: title,
statusCode: statusCode,
extensions: new Dictionary<string, object?>
{
{"traceId", traceId}
}
).ExecuteAsync(httpContext);

return true;
}

private static (int StatusCode, string Title) MapException(Exception exception)
{
return exception switch
{
ArgumentOutOfRangeException => (StatusCodes.Status400BadRequest, exception.Message),
_ => (StatusCodes.Status500InternalServerError, "Server error")
};
}
}
8 changes: 6 additions & 2 deletions JixMinApi/Features/Todo/TodoEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using JixMinApi.Features.Todo.Queries;
using MediatR;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System.Net.Mime;
Expand Down Expand Up @@ -40,12 +41,15 @@ public static void UseTodoEndpoints(this WebApplication app)
group.MapGet("/{id}", GetTodoByIdAsync)
.Produces<TodoDto>(StatusCodes.Status200OK)
.Produces<HttpValidationProblemDetails>(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status404NotFound);
.Produces(StatusCodes.Status404NotFound)
.Produces<ProblemDetails>(StatusCodes.Status500InternalServerError);


group.MapPost("/", CreateTodoAsync)
.Accepts<CreateTodoDto>(MediaTypeNames.Application.Json)
.Produces<TodoDto>(StatusCodes.Status201Created)
.Produces<HttpValidationProblemDetails>(StatusCodes.Status400BadRequest);
.Produces<HttpValidationProblemDetails>(StatusCodes.Status400BadRequest)
.Produces<ProblemDetails>(StatusCodes.Status500InternalServerError);

//group.MapDelete("/{id}", GetAllTodosAsync)
// .Produces(StatusCodes.Status204NoContent)
Expand Down
14 changes: 7 additions & 7 deletions JixMinApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@
builder.Services.AddHealthChecks();

var app = builder.Build();
app.UseHttpsRedirection();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
if (!app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseStatusCodePages();
app.UseExceptionHandler();
}

if (!app.Environment.IsDevelopment())
if (app.Environment.IsDevelopment())
{
app.UseHttpsRedirection();
app.UseExceptionHandler();
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseSerilogRequestLogging();
Expand Down
36 changes: 0 additions & 36 deletions JixMinApi/Shared/GlobalExceptionHandler.cs

This file was deleted.

0 comments on commit 2025980

Please sign in to comment.