I'm using ASP.NET Core. One of my controllers calls into services which throw various exceptions. I want to handle them in an exception filter (not middleware).
public class MyHandlerAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext c)
{
if (c.Exception is FooException) {
// redirect with arguments to here
}
else if (c.Exception is FooException) {
// redirect with arguments to there
}
else {
// redirect to main error action without arguments, as 500
}
base.OnException(c);
}
}
Unlike action filters, an exception filter doesn't give me access to the Controller
, so I can't do a c.Result = controller.RedirectTo...()
.
So how do I redirect to my error action?
Exception Filter provides an ability to handle the exception for all the method, controller classes in one place. Exception filters execute when some of the exceptions are thrown from an action. The exception can be anything. This is by creating a class that inherits from IExceptionFilter and FileAttribute interface.
The Exception Filter in the ASP.NET MVC Application is used to handle any exceptions that occur during the ASP.NET MVC Request processing pipeline. The ASP.NET MVC Framework provides one in-built attribute called HandleError which is basically used to handle the unhandled exception in the MVC application.
The HttpContext
is exposed on the ExceptionContext
, so you can use it for the redirection.
context.HttpContext.Response.Redirect("...");
There is also a Result
property, but I don't know if it'll be interpreted after the execution of the filter. It's worth a try though:
context.Result = new RedirectResult("...");
If it works, it should also work with RedirectToActionResult
or RedirectToRouteResult
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With