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.
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);
}
}
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