简体   繁体   English

带有自定义异常的ASP.NET MVC 2模型错误

[英]ASP.NET MVC 2 Model Errors with Custom Exceptions

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. .ToDescriptionMyExceptionEnum的扩展方法,可为异常错误详细信息提供枚举到字符串的映射。

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. 所以我用我的第一个ctor,它用给定的消息创建一个新的Exception。

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: 最后是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: AddModelError有两个重载:

  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? 我的异常确实有一个内部异常消息,所以我本以为HTML扩展会呈现该异常?

How do we handle custom exceptions with the ModelState then? 那么,我们如何使用ModelState处理自定义异常? Is using the second overload correct? 使用第二个过载是否正确?

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). 如果您有机会查看ModelError类的MVC源代码, 可以看到它具有公共字符串属性ErrorMessage ,该属性用于在验证发生时显示错误(在ValidationExtensions类中)。

In the overload constructor of ModelError(Exception exception) , though, it just sets the ErrorMessage property as empty string, rather than exception.Message . 但是,在ModelError(Exception exception)的重载构造函数中,它只是将ErrorMessage属性设置为空字符串,而不是exception.Message That's why you see nothing. 这就是为什么您什么都看不到的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM