diff --git a/blotztask-api/Data/Seeding/BlotzContextSeed.cs b/blotztask-api/Data/Seeding/BlotzContextSeed.cs index aabfbab..29e20ab 100644 --- a/blotztask-api/Data/Seeding/BlotzContextSeed.cs +++ b/blotztask-api/Data/Seeding/BlotzContextSeed.cs @@ -17,7 +17,7 @@ public static async Task SeedBlotzContextAsync(UserManager userManager, Ro // Seed admin user var defaultUser = new User { - UserName = "blotztest1", + UserName = "blotztest1@gmail.com", Email = "blotztest1@gmail.com", EmailConfirmed = true, }; diff --git a/blotztask-api/Middleware/ErrorHandlerMiddleware.cs b/blotztask-api/Middleware/ErrorHandlerMiddleware.cs new file mode 100644 index 0000000..0ff5f4c --- /dev/null +++ b/blotztask-api/Middleware/ErrorHandlerMiddleware.cs @@ -0,0 +1,40 @@ +using BlotzTask.Models.ApiResponse; + +public class ErrorHandlingMiddleware +{ + private readonly RequestDelegate _next; + + public ErrorHandlingMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + try + { + await _next(context); + } + + catch (UnauthorizedAccessException ex) + { + var errorMessage = string.IsNullOrWhiteSpace(ex.Message) ? "Unauthorized access." : ex.Message; + + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + await context.Response.WriteAsJsonAsync(new ApiResponse + { + Success = false, + Message = errorMessage + }); + } + + catch (Exception ex) + { + //TODO: Implement logging + Console.WriteLine($"Unhandled Exception: {ex}"); + + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsJsonAsync(new ApiResponse { Success = false, Message = "An error occurred while processing your request." }); + } + } +} diff --git a/blotztask-api/Models/ApiResponse/ApiResponse.cs b/blotztask-api/Models/ApiResponse/ApiResponse.cs new file mode 100644 index 0000000..4bb541e --- /dev/null +++ b/blotztask-api/Models/ApiResponse/ApiResponse.cs @@ -0,0 +1,8 @@ +namespace BlotzTask.Models.ApiResponse; + +public class ApiResponse +{ + public bool Success { get; set; } + public string Message { get; set; } = string.Empty; + public T? Data { get; set; } +} diff --git a/blotztask-api/Program.cs b/blotztask-api/Program.cs index 4138810..dfa2bf7 100644 --- a/blotztask-api/Program.cs +++ b/blotztask-api/Program.cs @@ -80,6 +80,7 @@ builder.Services.AddFluentValidationAutoValidation(); var app = builder.Build(); +app.UseMiddleware(); app.MapIdentityApi(); // Configure the HTTP request pipeline.