ASP.NET MVC 2 Model Errors with Custom Exceptions

*爱你&永不变心* 提交于 2019-12-24 00:34:22

问题


I have a custom exception class:

public class MyException: Exception
{
   public MyException(MyExceptionEnum myError) : base(myError.ToDescription()) { }
   public MyException(MyExceptionEnum myError, Exception innerException) : base(myError.ToDescription(), innerException) { }
}

.ToDescription is a extension method on MyExceptionEnum to provide enum-to-string mapping for the exception error details.

Here's how i throw it:

if (someCondition)
   throw new MyException(MyExceptionEnum.SomeError);

So i use my first ctor, which creates a new Exception with a given message.

Now onto the Controller:

[HttpPost]
public ActionResult UpdateFoo(Foo model)
{
   try
   {
      _fooService.UpdateModel(model);
      _unitOfWork.Commit();
   }
   catch(MyException myException)
   {
      ViewData.ModelState.AddModelError("ModelErrors", myException);
   }

   return View("Index", model);
}

And finally a snippet from the View:

<%: Html.ValidationMessage("ModelErrors") %>

Doesn't work (exception is thrown when i debug, error is added to model state, but nothing shown on page).

But if i change to the following line:

ViewData.ModelState.AddModelError("ModelErrors", myException.Message);

It works.

AddModelError has two overloads:

  1. string, Exception (doesn't work for me)
  2. string, string (works)

What is the use of the first overload then? My Exception does have an inner exception message, so i would have thought the HTML Extension would render that?

How do we handle custom exceptions with the ModelState then? Is using the second overload correct?


回答1:


Doesn't matter whether it's a custom exception or pre-defined one. It just doesn't work. If you have a chance to look at the MVC source code for ModelError class, you can see that it has an public string property ErrorMessage which is used to display the error when validation happens (in ValidationExtensions class).

In the overload constructor of ModelError(Exception exception), though, it just sets the ErrorMessage property as empty string, rather than exception.Message. That's why you see nothing.



来源:https://stackoverflow.com/questions/4029330/asp-net-mvc-2-model-errors-with-custom-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!