views:

30

answers:

1

Hi Guys,

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  A: 

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.

tshao
So are you saying this is a bug with MVC?
RPM1984
I believe so :)
tshao
+1 for clarifying that it doesn't seem to matter whether it's CLR/custom exception, and for checking the source!
Andrew Barber
Hahah, your right - bug confirmed. Thanks. :)
RPM1984