0

如何通过 MVCContrib.FluentController CheckValidCall(action) 中的操作传递异常?

    [ExportModelStateToTempData]
    public ActionResult Index(int itemId, int page)
    {
        return CheckValidCall(() => MyService.GetResults(itemId, page))
            .Valid(x => View(x))
            .Invalid(() => RedirectToAction(RestfulAction.Index));
    } 

当 GetResults() 抛出异常时,我想在视图中显示它。我已经厌倦了 ModelState

    <%if (ViewData.ModelState.ContainsKey("_FORM")) {%>
    <div class="notificationError">
        <%= ViewData.ModelState["_FORM"].Errors.FirstOrDefault().ErrorMessage %>            
    </div>
<%}%>

但 ModelState 是有效的并且不包含错误。有什么方法可以访问异常消息而不在 try-catch 块中包装服务方法?如果这有帮助,我的单元测试是检查 ModelState 失败,因为 TestController.ModelState.IsValid 为真:

    [Fact]
    public void ServiceExceptionIsConvertedToModelStateErrorInFluentController()
    {
        // Set up
        MockService.Setup(x => x.GetResults(It.IsAny<int>(), It.IsAny<int>()))
            .Throws(new InvalidOperationException("Mocked Service Exception"));

        // Excercise
        Assert.Throws<InvalidOperationException>(() => TestController.GetResults(1, 1));

        // Verify
        Assert.False(TestController.ModelState.IsValid);
        Assert.True(TestController.ModelState["_FORM"].Errors.Count > 0);
    }
4

1 回答 1

0

我设法通过覆盖 MvcContrib.FluentController.AbsteactFluentController.ExecuteCheckValidCall(Func action) 将异常传递给 ModelState:

    protected override object ExecuteCheckValidCall(Func<object> action)
    {
        try
        {
            return base.ExecuteCheckValidCall(action);
        }
        catch (Exception exception)
        {
            ModelState.AddModelError("_Exception", exception);
            return null;
        }
    }

由 CheckValidCall 调用。然而,该方法被描述为“仅用于测试目的且不应使用”的替代方法是覆盖 MvcContrib.FluentController.AbstractFluentController.CheckValidCall()。

于 2010-05-06T13:37:29.677 回答