diff --git a/dotnet/AipsWebApi/Controllers/UserController.cs b/dotnet/AipsWebApi/Controllers/UserController.cs index aa23ba4..f3a3f83 100644 --- a/dotnet/AipsWebApi/Controllers/UserController.cs +++ b/dotnet/AipsWebApi/Controllers/UserController.cs @@ -13,14 +13,7 @@ public class UserController : ControllerBase [HttpPost] public async Task> CreateUser(CreateUserCommand command, IDispatcher dispatcher, CancellationToken cancellationToken) { - try - { - var userId = await dispatcher.Execute(command, cancellationToken); - return Ok(userId.IdValue); - } - catch (ValidationException validationException) - { - return BadRequest(validationException.ValidationErrors); - } + var userId = await dispatcher.Execute(command, cancellationToken); + return Ok(userId.IdValue); } } \ No newline at end of file diff --git a/dotnet/AipsWebApi/Middleware/ExceptionHandlingMiddleware.cs b/dotnet/AipsWebApi/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..5b439de --- /dev/null +++ b/dotnet/AipsWebApi/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,47 @@ +using AipsCore.Domain.Common.Validation; + +namespace AipsWebApi.Middleware; + +public sealed class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + public ExceptionHandlingMiddleware( + RequestDelegate next, + ILogger logger) + { + _next = next; + _logger = logger; + } + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); + } + catch (ValidationException ex) + { + context.Response.StatusCode = StatusCodes.Status400BadRequest; + context.Response.ContentType = "application/json"; + + await context.Response.WriteAsJsonAsync(new + { + errors = ex.ValidationErrors + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Unhandled exception"); + + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + context.Response.ContentType = "application/json"; + + await context.Response.WriteAsJsonAsync(new + { + error = "Something went wrong" + }); + } + } +} diff --git a/dotnet/AipsWebApi/Program.cs b/dotnet/AipsWebApi/Program.cs index 43918ca..d1db72b 100644 --- a/dotnet/AipsWebApi/Program.cs +++ b/dotnet/AipsWebApi/Program.cs @@ -1,4 +1,5 @@ using AipsCore.Infrastructure.DI; +using AipsWebApi.Middleware; using DotNetEnv; Env.Load(); @@ -21,6 +22,8 @@ if (app.Environment.IsDevelopment()) } +app.UseMiddleware(); + app.UseAuthorization(); app.MapControllers();