Skip to content

Commit

Permalink
Fixed code smell
Browse files Browse the repository at this point in the history
  • Loading branch information
FrostyApeOne committed Oct 14, 2024
1 parent 533c597 commit e0b2481
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions PersonsApi/Middleware/ExceptionHandlerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ namespace PersonsApi.Middleware;

public class ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger)
{
private static readonly string? _responseContentType = "application/json";

public async Task InvokeAsync(HttpContext context)
{
try
Expand Down Expand Up @@ -46,7 +48,7 @@ private static async Task HandleNotFoundResponseAsync(HttpContext context)
{
if (!context.Response.HasStarted)
{
context.Response.ContentType = "application/json";
context.Response.ContentType = _responseContentType;
context.Response.StatusCode = StatusCodes.Status404NotFound;

var errorResponse = new CustomProblemDetails(HttpStatusCode.NotFound, "The requested resource could not be found.");
Expand All @@ -73,7 +75,7 @@ await httpContext.Response.WriteAsJsonAsync(new ValidationProblemDetails(excepti
private async Task HandleUnauthorizedResponseAsync(HttpContext context)
{
logger.LogWarning("Unauthorized access attempt detected.");
context.Response.ContentType = "application/json";
context.Response.ContentType = _responseContentType;
var errorResponse = new ErrorResponse
{
StatusCode = context.Response.StatusCode,
Expand All @@ -86,7 +88,7 @@ private async Task HandleUnauthorizedResponseAsync(HttpContext context)
private async Task HandleForbiddenResponseAsync(HttpContext context)
{
logger.LogWarning("Forbidden access attempt detected.");
context.Response.ContentType = "application/json";
context.Response.ContentType = _responseContentType;
var errorResponse = new ErrorResponse
{
StatusCode = context.Response.StatusCode,
Expand All @@ -98,7 +100,7 @@ private async Task HandleForbiddenResponseAsync(HttpContext context)
// Handle general exceptions (500 Internal Server Error)
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.ContentType = _responseContentType;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var errorResponse = new ErrorResponse
{
Expand Down

0 comments on commit e0b2481

Please sign in to comment.