简体   繁体   English

使用MVC的控制器中的错误处理

[英]Error handling in controllers with MVC

Does it make sense to do error handling and logging inside actions methods or handle the OnException method inside the controllers. 在操作方法内部执行错误处理和日志记录还是在控制器内部处理OnException方法是否有意义? One way means writing try/catches in all the action methods even when there is nothing to be done to recover from the error. 一种方法意味着即使无需采取任何措施来从错误中恢复,也要在所有操作方法中编写try / catches。 Handling this at the controller level would allow logging and redirection to an error handler page without writing try/catches inside all the action methods. 在控制器级别处理此问题将允许记录日志并重定向到错误处理程序页面,而无需在所有操作方法内编写try / catches。

Which method makes the most sense? 哪种方法最有意义? Here is example code of try/catches in an action method. 这是动作方法中try / catches的示例代码。

        [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. HandleError属性的形式已经有了一个开始。

I suggest you either subclass it or look at its implementation to come up with your custom one. 我建议您要么继承它,要么查看它的实现以提出您的自定义对象。 It's really simple. 真的很简单。

HandleErrorAttribute.cs HandleErrorAttribute.cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM