Flakron Bytyqi Flakron Bytyqi - 26 days ago 10
C# Question

.NET Core exception filter stops controller execution

I'm having a strange issue, or an expected one (just I didn't get it).

I've written an exception filter so it can catch a specific exception and add that exception message to the ModelState (to avoid using try/catch blocks in controllers).

The issue I'm having is that when the exception happens I get a blank screen instead of the view. It doesn't seem to continue where it left in the controller which I assume it should.

The filter:

public class ValidationFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.ExceptionHandled = true;
context.ModelState.AddModelError("", context.Exception.Message);
}
}

Answer

Seems rather logical to me. If you do the exception handling here, you need to ensure what you return as a response, since the flow was interrupted.

I suppose this is a model of what's going on:

try
{
   var model = SomeMethodThatThrowsException();
   return View(model);
}
catch
{
}

Now how would it be able to proceed with returning a view if the first line has thrown an exception unless you handle it right there and tell it what to do?

I am not 100% sure it's impossible to do what you want, but this seems rather logical (at least after working with previous versions of ASP.NET) flow.

Possible solutions

  • Redirect to a special error page with your exception as model e.g.
  • Transform to json and handle the result in SPA application.
  • If you need to add the errors to the view that is returned, you can decorate your function calls, either with a separate service or a simple delegate, e.g.
public void MyAction()
{
    MyModel model = ExecuteSafely(SomeMethodThatThrowsException());
    return View(model);
}

private MyModel ExecuteSafely(Func<MyModel> action)
{
    try
    {
       return action();
    }
    catch
    {
        // Add what you need to a model/view/etc. here
        return null;
    }
}

This is some example, so won't probably compile, but just give an indication of what I mean.