views:

67

answers:

1

Is there a use for the overload of AddModelError() that takes an Exception as a parameter?

If I include the following code in my controller:

ModelState.AddModelError( "", new Exception("blah blah blah") );
ModelState.AddModelError( "", "Something has went wrong" );

if (!ModelState.IsValid)
    return View( model );

And the following in my view:

<%= Html.ValidationSummary( "Please correct the errors and try again.") %>

Then only the text "Something has went wrong" is displayed in the error summary.

+1  A: 

Checking the source ModelError accepts both and the usage is for model type conversion failures.

In this particular case it's to go down the exception tree and grab inner exceptions when necessary to find the actual root error rather than a generic top level exception message.

foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList()) {
    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) {
        if (exception is FormatException) {
            string displayName = propertyMetadata.GetDisplayName();
            string errorMessageTemplate = GetValueInvalidResource(controllerContext);
            string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
            modelState.Errors.Remove(error);
            modelState.Errors.Add(errorMessage);
            break;
        }
    }
}

As you can see it's looping through the exception in the ModelError to find a FormatException. This is the only real reference to this I can find in both MVC 2 and MVC 3.

That said it's probably unnecessary for regular use.

BuildStarted