ASP.NET MVC 2模型误差与自定义异常 [英] ASP.NET MVC 2 Model Errors with Custom Exceptions

查看:176
本文介绍了ASP.NET MVC 2模型误差与自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义异常类:

public class MyException: Exception
{
   public MyException(MyExceptionEnum myError) : base(myError.ToDescription()) { }
   public MyException(MyExceptionEnum myError, Exception innerException) : base(myError.ToDescription(), innerException) { }
}

.ToDescription MyExceptionEnum A扩展方法来提供枚举到字符串的映射异常错误的详细信息

.ToDescription is a extension method on MyExceptionEnum to provide enum-to-string mapping for the exception error details.

以下是我扔了吧:

if (someCondition)
   throw new MyException(MyExceptionEnum.SomeError);

所以我用我的第一个构造函数,它创建了一个给定的消息的新的异常。

So i use my first ctor, which creates a new Exception with a given message.

现在到控制器:

[HttpPost]
public ActionResult UpdateFoo(Foo model)
{
   try
   {
      _fooService.UpdateModel(model);
      _unitOfWork.Commit();
   }
   catch(MyException myException)
   {
      ViewData.ModelState.AddModelError("ModelErrors", myException);
   }

   return View("Index", model);
}

终于从查看一个片段:

<%: 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 有两个重载:


  1. 字符串,异常(不为我工作)

  2. 字符串,字符串(作品)

什么是使用第一个重载的话?我的异常确实有一个内部异常的消息,所以我想到了HTML扩展将使呢?

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?

我们如何处理与随后的ModelState自定义异常?是使用第二个重载正确?

How do we handle custom exceptions with the ModelState then? Is using the second overload correct?

推荐答案

不要紧,无论它是一个自定义异常或pre定义之一。这是行不通的。
如果你有机会来看看MVC源$ C ​​$ C对于 ModelError 类,你可以看到它有一个公共字符串属性的的ErrorMessage 这是用来显示当错误发生的验证(在 ValidationExtensions 类)。

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(例外的例外),虽然,这只是设置在的ErrorMessage 属性作为空字符串,而不是 exception.Message 。这就是为什么你什么也看不到。

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.

这篇关于ASP.NET MVC 2模型误差与自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆