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:
- string, Exception (doesn't work for me)
- 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?