locked
Only exception handling in controller? RRS feed

  • Question

  • User1655654435 posted

    This is probably a question that has been done many times, but i find myself doing this some times:

    I wonder if it is right to double exception handling where if I create a post in a database from the controller:

    try
    {
       _postRepository.Create(post);
    }
    catch (Exception)
    {
        throw;
    }

    But then when I wrote the repository I also wrote an exception handling there. But whose responisbility is this(controller or repository), or should I actually write it both places?

    Thursday, April 5, 2018 1:35 PM

Answers

  • User1120430333 posted

    You could just use a base controller and do global exception handling where all exceptions are caught by the base controller, with no try/catches anywhere in the code. It wouldn't matter if the exception happened in the controller or the repository with all exceptions bubbling up to the base controller.

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 5, 2018 4:13 PM
  • User1400794712 posted

    Hi bluMarmalade,

    Do you mean that you want to add try-catch inside Create method?

    If there is something wrong inside _postRepository.Create() method, the try-catch outside it will catch this exception. It's unnecessary to write it both places. If you want to add try-catch statement inside Create method, it's also ok.

    Best Regards,

    Daisy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 6, 2018 9:50 AM

All replies

  • User475983607 posted

    This is probably a question that has been done many times, but i find myself doing this some times:

    I wonder if it is right to double exception handling where if I create a post in a database from the controller:

    try
    {
       _postRepository.Create(post);
    }
    catch (Exception)
    {
        throw;
    }

    But then when I wrote the repository I also wrote an exception handling there. But whose responisbility is this(controller or repository), or should I actually write it both places?

    You're not handling the exception.  This code works the same.

    _postRepository.Create(post);

    A rethrow pattern is generally used to capture state in an inner exception. 

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions

    Thursday, April 5, 2018 2:07 PM
  • User1120430333 posted

    You could just use a base controller and do global exception handling where all exceptions are caught by the base controller, with no try/catches anywhere in the code. It wouldn't matter if the exception happened in the controller or the repository with all exceptions bubbling up to the base controller.

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 5, 2018 4:13 PM
  • User1400794712 posted

    Hi bluMarmalade,

    Do you mean that you want to add try-catch inside Create method?

    If there is something wrong inside _postRepository.Create() method, the try-catch outside it will catch this exception. It's unnecessary to write it both places. If you want to add try-catch statement inside Create method, it's also ok.

    Best Regards,

    Daisy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 6, 2018 9:50 AM