Reputation: 3254
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);
}
}
Upvotes: 1
Views: 768
Reputation: 30205
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
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.
Upvotes: 1