开发者

Error handling in controllers with MVC

开发者 https://www.devze.com 2022-12-29 17:12 出处:网络
Does it make sense to do error handling and logging inside actions methods or handle the OnException method inside the controllers.One way means writing try/catches in all the action methods even when

Does it make sense to do error handling and logging inside actions methods or handle the OnException method inside the controllers. One way means writing try/catches in all the action methods even when there is nothing to be done to recover from the error. Handling this at the controller level would allow logging and redirection to an error handler page with开发者_Python百科out writing try/catches inside all the action methods.

Which method makes the most sense? Here is example code of try/catches in an action method.

        [HttpPost]
        public ActionResult Delete(int id)
        {
            using (new Tracer("Project Controller"))
            {
                try
                {
                    Logger.Write("Deleting project");
                    projService.DeleteProject(id);
                    TempData["message"] = "Project Deleted successfully";
                }
                catch (System.Exception ex)
                {
                    HandleException(ex, "Project could not be deleted.");
                }
                return RedirectToAction("List");
            }
        }


There is already a start in the form of the HandleError attribute.

I suggest you either subclass it or look at its implementation to come up with your custom one. It's really simple.

HandleErrorAttribute.cs

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号