I have this code.
public ActionResult Index() { ReceiptModel model = new ReceiptModel(); try { model = new ReceiptModel(context); } catch (BussinessException bex) { ModelState.AddModelError("Index", bex.MessageToDisplay); return View("Index"); } return View(model); }
BussinesException ir is returned from the database and then displayed to the user. I have to impose a try-catch method on each controller, which is a bit tedious. Is there an easier way to handle these exceptions?
PS All other exceptions are handled using HandleExceptionAttribute
UPDATE:
I used the Floradu88 approach. So now I have something like this.
public sealed class HandleBussinessExceptionAttribute : HandleErrorAttribute, IExceptionFilter { public override void OnException(ExceptionContext filterContext) { filterContext.Controller.TempData["UnhandledException"] = filterContext.Exception; filterContext.ExceptionHandled = true; ((Controller)filterContext.Controller).ModelState.AddModelError( ((BussinessException)filterContext.Exception).Code.ToString(), ((BussinessException)filterContext.Exception).MessageToDisplay ); filterContext.Result = new ViewResult { ViewName = this.View, TempData = filterContext.Controller.TempData, ViewData = filterContext.Controller.ViewData, }; } }
and in the Controller action I will put
[HandleBussinessExceptionAttribute(Order = 2, ExceptionType = typeof(BussinessException), View = "Login")]
I also tried an exception handler:
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(filterContext.RouteData));
and then handle the error in the action using ModelState.IsValid , but the values ββto the action will be null. Therefore, at the moment I am using the first approach. When I have a little more time, I will try to fix the second approach.
source share