Add Global Exception Handling
This commit is contained in:
@@ -11,7 +11,7 @@ namespace Imprink.WebApi.Controllers.Users;
|
||||
public class UserRoleController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[Authorize]
|
||||
[HttpGet("/me")]
|
||||
[HttpGet("me")]
|
||||
public async Task<IActionResult> GetMyRoles()
|
||||
{
|
||||
var claims = User.Claims as Claim[] ?? User.Claims.ToArray();
|
||||
@@ -23,7 +23,7 @@ public class UserRoleController(IMediator mediator) : ControllerBase
|
||||
}
|
||||
|
||||
[Authorize(Roles = "Admin")]
|
||||
[HttpPost("/set")]
|
||||
[HttpPost("set")]
|
||||
public async Task<IActionResult> SetUserRole(SetUserRoleCommand command)
|
||||
{
|
||||
var userRole = await mediator.Send(command);
|
||||
@@ -35,7 +35,7 @@ public class UserRoleController(IMediator mediator) : ControllerBase
|
||||
}
|
||||
|
||||
[Authorize(Roles = "Admin")]
|
||||
[HttpPost("/unset")]
|
||||
[HttpPost("unset")]
|
||||
public async Task<IActionResult> UnsetUserRole(DeleteUserRoleCommand command)
|
||||
{
|
||||
var userRole = await mediator.Send(command);
|
||||
|
||||
75
src/Imprink.WebApi/Middleware/ExceptionHandlingMiddleware.cs
Normal file
75
src/Imprink.WebApi/Middleware/ExceptionHandlingMiddleware.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Imprink.Application.Exceptions;
|
||||
|
||||
namespace Imprink.WebApi.Middleware;
|
||||
|
||||
public class ExceptionHandlingMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<ExceptionHandlingMiddleware> logger)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var (_, _, shouldLog) = GetStatusCodeAndMessage(ex);
|
||||
|
||||
if (shouldLog)
|
||||
{
|
||||
logger.LogError(ex, "An unhandled exception occurred: {Message}", ex.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation("Handled: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
await HandleExceptionAsync(context, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
|
||||
var (statusCode, message, _) = GetStatusCodeAndMessage(exception);
|
||||
|
||||
context.Response.StatusCode = (int)statusCode;
|
||||
|
||||
var response = new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
message,
|
||||
timestamp = DateTime.UtcNow,
|
||||
}
|
||||
};
|
||||
|
||||
var jsonResponse = JsonSerializer.Serialize(response, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
});
|
||||
|
||||
await context.Response.WriteAsync(jsonResponse);
|
||||
}
|
||||
|
||||
private static (HttpStatusCode statusCode, string message, bool shouldLog) GetStatusCodeAndMessage(Exception exception)
|
||||
{
|
||||
return exception switch
|
||||
{
|
||||
NotFoundException => (HttpStatusCode.NotFound, exception.Message, false),
|
||||
_ => (HttpStatusCode.InternalServerError, "An internal server error occurred", true)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static class GlobalExceptionHandlingMiddlewareExtensions
|
||||
{
|
||||
public static void UseGlobalExceptionHandling(this IApplicationBuilder builder)
|
||||
{
|
||||
builder.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
}
|
||||
}
|
||||
@@ -140,13 +140,13 @@ public static class Startup
|
||||
}
|
||||
}
|
||||
|
||||
app.UseGlobalExceptionHandling();
|
||||
app.UseRequestTiming();
|
||||
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user