Skip to content

Commit

Permalink
feat: add errorHandlingMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikoo-Asadnejad committed May 3, 2024
1 parent f3653f7 commit 2120521
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
36 changes: 36 additions & 0 deletions Src/Product.API/Middlewares/ErrorHandlingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Product.API.Middlewares
{
public class ErrorHandlingMiddleware : IMiddleware
{

private readonly ILogger _loggerService;
public ErrorHandlingMiddleware(ILogger loggerService)
{
_loggerService = loggerService;
}

public async Task InvokeAsync(HttpContext contex , RequestDelegate next)
{
try
{
await next(contex);
}
catch (Exception ex)
{
_loggerService.LogError(ex , $"An Error Captured by ErrorHandlingMiddleware : {ex.Message}");
await CreateErrorResponse(contex);
}
}
private static async Task CreateErrorResponse( HttpContext contex)
{
contex.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
contex.Response.ContentType = "application/json; charset=utf-8";

}

}
}
4 changes: 0 additions & 4 deletions Src/Product.API/Product.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,4 @@
</Content>
</ItemGroup>

<ItemGroup>
<Folder Include="Middlewares\" />
</ItemGroup>

</Project>

0 comments on commit 2120521

Please # to comment.