Skip to content

Commit

Permalink
add HandleControllerExceptionAttribute
Browse files Browse the repository at this point in the history
  • Loading branch information
osmanaslancan committed Jul 25, 2023
1 parent 1e47110 commit d4c953a
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/Serenity.Net.Web/Mvc/HandleControllerExceptionAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Serenity.Services;

/// <summary>
/// An exception filter attribute to handle controller exceptions and return as view.
/// </summary>
public class HandleControllerExceptionAttribute : ExceptionFilterAttribute
{
/// <inheritdoc/>
public override void OnException(ExceptionContext context)
{
context.ExceptionHandled = true;
var result = context.Exception.ConvertToResponse<ServiceResponse>(context.HttpContext);
context.Result = new ViewResult()
{
ViewName = "~/Views/Errors/ValidationError.cshtml",
ViewData = new ViewDataDictionary<ValidationError>(new EmptyModelMetadataProvider(), context.ModelState)
{
Model = new ValidationError(result.Error.Code, result.Error.Message),
}
};
}
}

0 comments on commit d4c953a

Please sign in to comment.