我已经花了几个小时来解决这个问题。我的解决方案基于以下愿望/要求:
- 在所有JSON控制器操作中都没有重复的样板错误处理代码。
- 保留HTTP(错误)状态代码。为什么?因为较高级别的关注不应影响较低级别的实现。
- 当服务器上发生错误/异常时,能够获取JSON数据。为什么?因为我可能想要丰富的错误信息。例如错误消息,特定于域的错误状态代码,堆栈跟踪(在调试/开发环境中)。
- 客户端易于使用-最好使用jQuery。
我创建了一个HandleErrorAttribute(有关详细说明,请参见代码注释)。省略了包括“用法”在内的一些细节,因此代码可能无法编译。我在Global.asax.cs中的应用程序初始化期间将过滤器添加到全局过滤器中,如下所示:
GlobalFilters.Filters.Add(new UnikHandleErrorAttribute());
属性:
namespace Foo
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class FooHandleErrorAttribute : HandleErrorAttribute
{
private readonly TraceSource _TraceSource;
public FooHandleErrorAttribute(TraceSource traceSource)
{
if (traceSource == null)
throw new ArgumentNullException(@"traceSource");
_TraceSource = traceSource;
}
public TraceSource TraceSource
{
get
{
return _TraceSource;
}
}
public FooHandleErrorAttribute()
{
var className = typeof(FooHandleErrorAttribute).FullName ?? typeof(FooHandleErrorAttribute).Name;
_TraceSource = new TraceSource(className);
}
public override void OnException(ExceptionContext filterContext)
{
var actionMethodInfo = GetControllerAction(filterContext.Exception);
if(actionMethodInfo == null) return;
var controllerName = filterContext.Controller.GetType().FullName;
var actionName = actionMethodInfo.Name;
var traceMessage = string.Format(@"Unhandled exception from {0}.{1} handled in {2}. Exception: {3}", controllerName, actionName, typeof(FooHandleErrorAttribute).FullName, filterContext.Exception);
_TraceSource.TraceEvent(TraceEventType.Error, TraceEventId.UnhandledException, traceMessage);
if (actionMethodInfo.ReturnType != typeof(JsonResult)) return;
var jsonMessage = FooHandleErrorAttributeResources.Error_Occured;
if (filterContext.Exception is MySpecialExceptionWithUserMessage) jsonMessage = filterContext.Exception.Message;
filterContext.Result = new JsonResult
{
Data = new
{
message = jsonMessage,
stacktrace = MyEnvironmentHelper.IsDebugging ? filterContext.Exception.StackTrace : null
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
base.OnException(filterContext);
}
private static MethodInfo GetControllerAction(Exception exception)
{
var stackTrace = new StackTrace(exception);
var frames = stackTrace.GetFrames();
if(frames == null) return null;
var frame = frames.FirstOrDefault(f => typeof(IController).IsAssignableFrom(f.GetMethod().DeclaringType));
if (frame == null) return null;
var actionMethod = frame.GetMethod();
return actionMethod as MethodInfo;
}
}
}
我为客户端的易用性开发了以下jQuery插件:
(function ($, undefined) {
"using strict"
$.FooGetJSON = function (url, data, success, error) {
/// <summary>
/// **********************************************************
/// * UNIK GET JSON JQUERY PLUGIN. *
/// **********************************************************
/// This plugin is a wrapper for jQuery.getJSON.
/// The reason is that jQuery.getJSON success handler doesn't provides access to the JSON object returned from the url
/// when a HTTP status code different from 200 is encountered. However, please note that whether there is JSON
/// data or not depends on the requested service. if there is no JSON data (i.e. response.responseText cannot be
/// parsed as JSON) then the data parameter will be undefined.
///
/// This plugin solves this problem by providing a new error handler signature which includes a data parameter.
/// Usage of the plugin is much equal to using the jQuery.getJSON method. Handlers can be added etc. However,
/// the only way to obtain an error handler with the signature specified below with a JSON data parameter is
/// to call the plugin with the error handler parameter directly specified in the call to the plugin.
///
/// success: function(data, textStatus, jqXHR)
/// error: function(data, jqXHR, textStatus, errorThrown)
///
/// Example usage:
///
/// $.FooGetJSON('/foo', { id: 42 }, function(data) { alert('Name :' + data.name)
/// </summary>
// Call the ordinary jQuery method
var jqxhr = $.getJSON(url, data, success)
// Do the error handler wrapping stuff to provide an error handler with a JSON object - if the response contains JSON object data
if (typeof error !== "undefined") {
jqxhr.error(function(response, textStatus, errorThrown) {
try {
var json = $.parseJSON(response.responseText)
error(json, response, textStatus, errorThrown)
} catch(e) {
error(undefined, response, textStatus, errorThrown)
}
})
}
// Return the jQueryXmlHttpResponse object
return jqxhr
}
})(jQuery)
从这一切中我能得到什么?最终的结果是
- 我的控制器操作都没有对HandleErrorAttributes的要求。
- 我的控制器操作均未包含任何重复的样板错误处理代码。
- 我有一个单点的错误处理代码,可让我轻松更改日志记录和其他与错误处理相关的内容。
- 一个简单的要求:返回JsonResult的控制器动作必须具有返回类型JsonResult,而不是诸如ActionResult之类的基本类型。原因:请参见FooHandleErrorAttribute中的代码注释。
客户端示例:
var success = function(data) {
alert(data.myjsonobject.foo);
};
var onError = function(data) {
var message = "Error";
if(typeof data !== "undefined")
message += ": " + data.message;
alert(message);
};
$.FooGetJSON(url, params, onSuccess, onError);
欢迎评论!我可能有一天会在博客上介绍这种解决方案...