代码之家  ›  专栏  ›  技术社区  ›  David Gardiner

目的ModelState.AddModelError带异常参数

  •  6
  • David Gardiner  · 技术社区  · 14 年前

    有没有一个超载的使用 AddModelError ()将异常作为参数?

    如果在控制器中包含以下代码:

    ModelState.AddModelError( "", new Exception("blah blah blah") );
    ModelState.AddModelError( "", "Something has went wrong" );
    
    if (!ModelState.IsValid)
        return View( model );
    

    在我看来:

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

    1 回复  |  直到 14 年前
        1
  •  3
  •   Buildstarted    14 年前

    检查源ModelError会同时接受这两种情况,并且用于模型类型转换失败。

    在这种特殊的情况下,需要沿着异常树并在必要时获取内部异常,以查找实际的根错误,而不是一般的顶级异常消息。

    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;
            }
        }
    }
    

    正如您所看到的,它在ModelError中遍历异常以查找FormatException。这是我在mvc2和mvc3中找到的唯一一个真正的引用。

    也就是说它可能不需要经常使用。