我如何创建一个 fubumvc 行为来包装具有特定返回类型的操作,如果在执行操作时发生异常,那么该行为会记录异常并填充返回对象上的某些字段?我尝试了以下方法:
public class JsonExceptionHandlingBehaviour : IActionBehavior
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private readonly IActionBehavior _innerBehavior;
private readonly IFubuRequest _request;
public JsonExceptionHandlingBehaviour(IActionBehavior innerBehavior, IFubuRequest request)
{
_innerBehavior = innerBehavior;
_request = request;
}
public void Invoke()
{
try
{
_innerBehavior.Invoke();
var response = _request.Get<AjaxResponse>();
response.Success = true;
}
catch(Exception ex)
{
logger.ErrorException("Error processing JSON request", ex);
var response = _request.Get<AjaxResponse>();
response.Success = false;
response.Exception = ex.ToString();
}
}
public void InvokePartial()
{
_innerBehavior.InvokePartial();
}
}
但是,虽然我从请求中获得了 AjaxResponse
对象,但我所做的任何更改都不会发送回客户端。此外,操作抛出的任何异常都不会到此为止,请求在执行到达 catch block 之前终止。我做错了什么?
为了完整起见,该行为与我的 WebRegistry 中的以下内容相关联:
Policies
.EnrichCallsWith<JsonExceptionHandlingBehaviour>(action =>
typeof(AjaxResponse).IsAssignableFrom(action.Method.ReturnType));
AjaxResponse 看起来像:
public class AjaxResponse
{
public bool Success { get; set; }
public object Data { get; set; }
public string Exception { get; set; }
}
最佳答案
不幸的是,这不适用于当前版本的 FubuMVC。原因是对 _innerBehavior.Invoke() 的调用将沿着行为链的其余部分进行,包括将 JSON 输出呈现回客户端的调用。
使用当前的 FubuMVC,您无法在执行渲染输出行为之前包装行为并修改其输出。
我刚刚和 Jeremy (Miller) 谈过这个,我们将把这个功能添加到 FubuMVC 中,这样你就可以包装一个特定的行为(在本例中是调用 Action 的行为)而不是包装整个行为链(这就是你现在正在发生的事情)。
当我们添加此功能后,我会在此处就此 StackOverflow 问题发表评论。
关于fubumvc - 如何创建异常包装 fubumvc 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2496416/