Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Declarative Redirect On Error

I have been capturing exceptions and redirecting users to an error page. I pass the exception message and a return URL to tell the user what happened and allow them to return another page.

        try
        {
            return action(parameters);
        }
        catch (Exception exception)
        {
            ErrorViewModel errorModel = new ErrorViewModel();
            errorModel.ErrorMessage = "An error occured while doing something.";
            errorModel.ErrorDetails = exception.Message;
            errorModel.ReturnUrl = Url.Action("Controller", "Action");
            return RedirectToAction("Index", "Error", errorModel);
        }

This seems like way too much code to wrap around every action. I am using a global filter for errors:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        HandleErrorAttribute attribute = new HandleErrorAttribute();
        filters.Add(attribute);
    }

and I have my web.config setup like this:

<customErrors mode="On" defaultRedirect="~/Error/Unknown">

But, this only works for unhandled exceptions.

I want exceptions to cause a redirect to an error controller/action taking a parameter holding the exception details. It would be nice if I could indicate the return URL on a action-by-action basis, or to have a default if none is provided.

like image 787
Travis Parks Avatar asked Feb 21 '23 21:02

Travis Parks


1 Answers

Instead of putting a try catch in every action, you could override the OnException event of the controller. That event contains all the exception details. All of you other settings look right.

    [HandleError]
    public class AccountController : Controller
    {
       [HttpPost]
       public ActionResult YourAction(SomeModel model)
        {
            //do stuff but don't catch exception
            return View();
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            EventLog.WriteEntry("YourProjectEventName", filterContext.Exception.ToString(), EventLogEntryType.Error);
            base.OnException(filterContext);
       }
}
like image 194
Ryand.Johnson Avatar answered Feb 27 '23 16:02

Ryand.Johnson