Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend error handling implementation #102

Merged
merged 5 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion blotztask-api/Data/Seeding/BlotzContextSeed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// Seed admin user
var defaultUser = new User
{
UserName = "blotztest1",
UserName = "blotztest1@gmail.com",
Email = "blotztest1@gmail.com",
EmailConfirmed = true,
};
Expand Down Expand Up @@ -46,7 +46,7 @@
new Claim("CanDelete", "true")
};

await userManager.AddClaimsAsync(userAdded, claims);

Check warning on line 49 in blotztask-api/Data/Seeding/BlotzContextSeed.cs

View workflow job for this annotation

GitHub Actions / build-and-test-backend

Possible null reference argument for parameter 'user' in 'Task<IdentityResult> UserManager<User>.AddClaimsAsync(User user, IEnumerable<Claim> claims)'.
user = userAdded;
Console.WriteLine("User creation Success.");
}
Expand Down
40 changes: 40 additions & 0 deletions blotztask-api/Middleware/ErrorHandlerMiddleware.cs
Original file line number Diff line number Diff line change
@@ -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<object>
{
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<object> { Success = false, Message = "An error occurred while processing your request." });
}
}
}
8 changes: 8 additions & 0 deletions blotztask-api/Models/ApiResponse/ApiResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace BlotzTask.Models.ApiResponse;

public class ApiResponse<T>
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public T? Data { get; set; }
}
1 change: 1 addition & 0 deletions blotztask-api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@

builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultKeyVaultSecretManager());

var client = new SecretClient(new Uri(keyVaultEndpoint), new DefaultAzureCredential());

Check warning on line 58 in blotztask-api/Program.cs

View workflow job for this annotation

GitHub Actions / build-and-test-backend

Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'.
builder.Services.AddDbContext<BlotzTaskDbContext>(options => options.UseSqlServer(client.GetSecret("db-string-connection").Value.Value.ToString()));

}
Expand All @@ -80,6 +80,7 @@
builder.Services.AddFluentValidationAutoValidation();

var app = builder.Build();
app.UseMiddleware<ErrorHandlingMiddleware>();

app.MapIdentityApi<User>();
// Configure the HTTP request pipeline.
Expand Down
Loading