Skip to content

Commit

Permalink
Changed exception handler to use the new IExceptionHandler feature in…
Browse files Browse the repository at this point in the history
… NET8
  • Loading branch information
babaktaremi committed Nov 26, 2023
1 parent 05a02b2 commit cf0d730
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 94 deletions.
2 changes: 1 addition & 1 deletion CleanArcTemplate.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<metadata>

<id>Bobby.CleanArcTemplate</id>
<version>5.0.0</version>
<version>5.0.1</version>
<title>Clean Architecture Solution Template</title>
<authors>BabakTaremi</authors>
<description>Clean Architecture Solution Template for and .NET 8. With many features available out of the box</description>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,6 @@ public async Task<IActionResult> CreateUser(UserCreateCommand model)
return base.OperationResult(command);
}

//[HttpPost("ConfirmPhoneNumber")]
//public async Task<IActionResult> ConfirmPhoneNumber(ConfirmUserPhoneNumberViewModel model)
//{
// var command = await _mediator.Send(new ConfirmPhoneNumberCommand(model.UserKey, model.Code));

// return OperationResult(command);
//}

[HttpPost("TokenRequest")]
public async Task<IActionResult> TokenRequest(UserTokenRequestQuery model)
Expand Down
5 changes: 2 additions & 3 deletions src/API/CleanArc.Web.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
.AddWebFrameworkServices();

builder.Services.RegisterValidatorsAsServices();
builder.Services.AddExceptionHandler<ExceptionHandler>();


#region Plugin Services Configuration
Expand All @@ -84,9 +85,7 @@
app.UseDeveloperExceptionPage();
}

app.UseCustomExceptionHandler();


app.UseExceptionHandler(_=>{});
app.UseSwaggerAndUI();

app.MapCarter();
Expand Down

This file was deleted.

56 changes: 56 additions & 0 deletions src/API/CleanArc.WebFramework/Middlewares/ExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using CleanArc.Application.Models.ApiResult;
using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.ComponentModel.DataAnnotations;
using CleanArc.SharedKernel.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace CleanArc.WebFramework.Middlewares;

public class ExceptionHandler(ILogger<ExceptionHandler> logger,IWebHostEnvironment environment) : IExceptionHandler
{

public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken)
{
if (exception is FluentValidation.ValidationException validationException)
{
context.Response.StatusCode = StatusCodes.Status422UnprocessableEntity;

var errors = new Dictionary<string, List<string>>();

foreach (var validationExceptionError in validationException.Errors)
{
if (!errors.ContainsKey(validationExceptionError.PropertyName))
errors.Add(validationExceptionError.PropertyName, new List<string>() { validationExceptionError.ErrorMessage });
else
errors[validationExceptionError.PropertyName].Add(validationExceptionError.ErrorMessage);

}

var apiResult = new ApiResult<IDictionary<string, List<string>>>(false, ApiResultStatusCode.EntityProcessError, errors, ApiResultStatusCode.EntityProcessError.ToDisplay());

context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsJsonAsync(apiResult, cancellationToken: cancellationToken);

return true;
}

logger.LogError(exception,"Error captured in global exception handler");

context.Response.StatusCode = StatusCodes.Status500InternalServerError;

if (environment.IsDevelopment())
return false;

context.Response.ContentType = "application/problem+json";
var response = new ApiResult(false,
ApiResultStatusCode.ServerError, "Server Error");
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(response, cancellationToken: cancellationToken);

return true;
}
}

0 comments on commit cf0d730

Please sign in to comment.