如何通过 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);
}