Skip to content

Commit

Permalink
Feat: Added Middleware for catching double register
Browse files Browse the repository at this point in the history
error; now returns general
error. Still needs work
  • Loading branch information
Legolas2222 committed Oct 19, 2023
1 parent 8085bc2 commit 9e181c2
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
32 changes: 32 additions & 0 deletions TodoistClone.Api/Middleware/ErrorHandlingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace TodoistClone.Api.Middleware;

public class ErrorHandlingMiddlware
{
private readonly RequestDelegate _next;

public ErrorHandlingMiddlware(RequestDelegate next) {
_next = next;
}

public async Task Invoke(HttpContext context) {
try {
await _next(context);
}
catch (Exception exception) {
await HandleExceptionAsync(context, exception);
}
}

private static Task HandleExceptionAsync(HttpContext context, Exception exception) {
var code = HttpStatusCode.InternalServerError;
var result = JsonSerializer.Serialize(new { error = "An error occured while processing your request." });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}

6 changes: 5 additions & 1 deletion TodoistClone.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using TodoistClone.Api.Middleware;
using TodoistClone.Application;
using TodoistClone.Infrastructure;

Expand All @@ -22,11 +23,14 @@
}
*/
var app = builder.Build();

{
//app.UseHttpsRedirection();
app.UseMiddleware<ErrorHandlingMiddlware>();

app.UseAuthorization();

app.MapControllers();

app.Run();

}

0 comments on commit 9e181c2

Please sign in to comment.