[英]Passing Errors (Exception Messages) from Repository to Controller Action in asp.net MVC2
I have been trying to develop an app using the repository pattern like in the Nerd Dinner application however I would like to handle exceptions in the repository and pass the exception messages back to the controller so that I can output the message in a nice page to the user. 我一直在尝试使用像Nerd Dinner应用程序中的存储库模式开发一个应用程序但是我想处理存储库中的异常并将异常消息传递回控制器,以便我可以在一个很好的页面中输出消息到用户。
How do I pass back this exception message, or even pass that an exception has occured in the repository. 如何传回此异常消息,甚至传递存储库中发生的异常。
http://www.asp.net/ajaxlibrary/jquery_errors.ashx http://www.asp.net/ajaxlibrary/jquery_errors.ashx
In the following example from the above url, "_repository.HasErrors" is used as a check but I want to know what the implementaion of this is in the repository in C# as I dont know how this is implemented and also if its possible to also get the error message as well. 在以下来自上面的url的示例中,“_repository.HasErrors”用作检查,但我想知道它在C#中的存储库中的实现是什么,因为我不知道如何实现它以及它是否也可能也得到错误消息。
01.// GET: /HandlejQueryErrors/Contact/Create
02.public ActionResult Create()
03.{
04. return View();
05.}
06.
07.// POST: /HandlejQueryErrors/Contact/Create
08.[HttpPost]
09.public ActionResult Create(ContactViewModel viewModel)
10.{
11. var response = new AjaxResponseViewModel();
12.
13. try
14. {
15. var contact = _repository.SaveOrUpdate(viewModel);
16. if (!_repository.HasErrors)
17. {
18. response.Success = true;
19. response.Message = "Your contact was successfully created!";
20. }
21. else
22. {
23. response.Message = "There was an error updating your contact!";
24. }
25. }
26. catch (Exception exception)
27. {
28. response.Success = false;
29. response.Messages exception.Message;
30. }
31.
32. return Json(response);
33.}
Thanks in advance. 提前致谢。
You could allow your repository's exceptions to fall through, and override your controller's OnActionExecuted method to handle specific errors for you. 您可以允许存储库的异常通过,并覆盖控制器的OnActionExecuted方法以处理特定的错误。 Example: 例:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception is RepositoryException)
{
filterContext.ExceptionHandled = true;
filterContext.Result = View("Exception", filterContext.Exception);
}
base.OnActionExecuted(filterContext);
}
So, in general in ASP.NET MVC you need to handle 2 kinds of errors: Validation errors, and System errors. 因此,通常在ASP.NET MVC中,您需要处理两种错误:验证错误和系统错误。
For System errors, those occurring because of some system rules violation (like foreign key constraint violation in database during insert), you should use try-catche operator and then pass them to the view in some way to show them to the user. 对于系统错误,由于某些系统规则违规而发生的错误(如插入期间数据库中的外键约束违规),您应该使用try-catche运算符,然后以某种方式将它们传递给视图以向用户显示它们。
For validation errors, you should read about ASP.NET MVC Validation: 对于验证错误,您应该阅读有关ASP.NET MVC验证的信息:
So, as a conclusion, think of separating the concerns about domain/business functionality from the concerns related to validation. 因此,作为结论,考虑将关于域/业务功能的问题与与验证相关的问题分开。 The only common thing they should have (in the perfect scenario) is a view where you show the results of validation. 他们应该拥有的唯一常见事物(在完美的场景中)是一个显示验证结果的视图。
Personally I (taking 2-nd approach) even do a save in validation, so that Validation implementation knows about domain/business logic and manipulates it to validate all the rules. 我个人(采用第二种方法)甚至在验证中进行保存,以便验证实现了解域/业务逻辑并操纵它来验证所有规则。 In the end of validation, if all rules were met, then it tries to save the data, and returns the validation error message in case of non-success. 在验证结束时,如果满足所有规则,则它会尝试保存数据,并在不成功的情况下返回验证错误消息。 This is also a good start to go further and even localize your custom validation messages. 这也是进一步发展甚至本地化自定义验证消息的良好开端。
I hope this helps! 我希望这有帮助!
I personally still like the GetRuleViolations() approach started by ScottGu and would simply follow this through on the Repository. 我个人仍然喜欢ScottGu开始的GetRuleViolations()方法,并且只需在存储库中执行此操作。
In the controller I would do (pseudo here): 在控制器中我会做(伪在这里):
[HttpPost]
public ActionResult ControllerAction(MyViewModel viewModel)
{
ModelState.AddRuleViolations(viewModel.GetRuleViolations);
if (!ModelState.IsValid)
{
return View();
}
// Perform repository action (pseudo code to follow)
_repository.ClearErrorState();
_repository.DoSomething();
ModelState.AddRuleViolation(repository.GetRuleViolations());
if (!ModelState.IsValid)
{
return View();
}
return RedirectToAction("Foo","Bar");
}
class Repository
{
List<RuleViolation> _errors = new List<RuleViolation>();
public void ClearErrorState()
{
_errors.Clear();
}
public void DoSomething(...)
{
try
{
DoSomthingThatFails();
}
catch (Exception ex)
{
_errors.Add(new RuleViolation(null, "Error while saving customer");
_errors.Add(new RuleViolation("SSN", "SSN must be unique"); // This one I struggle with as bad design, tying UI element to data elements is bad, so generally I try to prevent everything when checking the viewmodel and only catch general (unforeseen) errors here.
}
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
return _errors;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.