मैंने इस समस्या को हल करने में कुछ घंटे व्यतीत किए हैं। मेरा समाधान निम्न इच्छाओं/आवश्यकताओं पर आधारित है:
- सभी JSON नियंत्रक कार्यों में पुनरावर्तित बॉयलरप्लेट त्रुटि हैंडलिंग कोड नहीं है।
- HTTP (त्रुटि) स्थिति कोड को सुरक्षित रखें। क्यूं कर? क्योंकि उच्च स्तर की चिंताओं को निम्न स्तर के कार्यान्वयन को प्रभावित नहीं करना चाहिए।
- सर्वर पर त्रुटि/अपवाद होने पर JSON डेटा प्राप्त करने में सक्षम हो। क्यूं कर? क्योंकि मुझे समृद्ध त्रुटि जानकारी चाहिए। जैसे त्रुटि संदेश, डोमेन विशिष्ट त्रुटि स्थिति कोड, स्टैक ट्रेस (डीबग/विकास पर्यावरण में)।
- उपयोग की आसानी क्लाइंट पक्ष - jQuery का उपयोग कर बेहतर।
मैं एक हैंडलरर एट्रिब्यूट बनाता हूं (विवरण के स्पष्टीकरण के लिए कोड टिप्पणियां देखें)। "उपयोग" सहित कुछ विवरण छोड़ दिए गए हैं, इसलिए कोड संकलित नहीं हो सकता है। मैं फिल्टर इस तरह 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;
/// <summary>
/// Generel error handler attribute for Foo MVC solutions.
/// It handles uncaught exceptions from controller actions.
/// It outputs trace information.
/// If custom errors are enabled then the following is performed:
/// <ul>
/// <li>If the controller action return type is <see cref="JsonResult"/> then a <see cref="JsonResult"/> object with a <c>message</c> property is returned.
/// If the exception is of type <see cref="MySpecialExceptionWithUserMessage"/> it's message will be used as the <see cref="JsonResult"/> <c>message</c> property value.
/// Otherwise a localized resource text will be used.</li>
/// </ul>
/// Otherwise the exception will pass through unhandled.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class FooHandleErrorAttribute : HandleErrorAttribute
{
private readonly TraceSource _TraceSource;
/// <summary>
/// <paramref name="traceSource"/> must not be null.
/// </summary>
/// <param name="traceSource"></param>
public FooHandleErrorAttribute(TraceSource traceSource)
{
if (traceSource == null)
throw new ArgumentNullException(@"traceSource");
_TraceSource = traceSource;
}
public TraceSource TraceSource
{
get
{
return _TraceSource;
}
}
/// <summary>
/// Ctor.
/// </summary>
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);
// It's probably an error if we cannot find a controller action. But, hey, what should we do about it here?
if(actionMethodInfo == null) return;
var controllerName = filterContext.Controller.GetType().FullName; // filterContext.RouteData.Values[@"controller"];
var actionName = actionMethodInfo.Name; // filterContext.RouteData.Values[@"action"];
// Log the exception to the trace source
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);
// Don't modify result if custom errors not enabled
//if (!filterContext.HttpContext.IsCustomErrorEnabled)
// return;
// We only handle actions with return type of JsonResult - I don't use AjaxRequestExtensions.IsAjaxRequest() because ajax requests does NOT imply JSON result.
// (The downside is that you cannot just specify the return type as ActionResult - however I don't consider this a bad thing)
if (actionMethodInfo.ReturnType != typeof(JsonResult)) return;
// Handle JsonResult action exception by creating a useful JSON object which can be used client side
// Only provide error message if we have an MySpecialExceptionWithUserMessage.
var jsonMessage = FooHandleErrorAttributeResources.Error_Occured;
if (filterContext.Exception is MySpecialExceptionWithUserMessage) jsonMessage = filterContext.Exception.Message;
filterContext.Result = new JsonResult
{
Data = new
{
message = jsonMessage,
// Only include stacktrace information in development environment
stacktrace = MyEnvironmentHelper.IsDebugging ? filterContext.Exception.StackTrace : null
},
// Allow JSON get requests because we are already using this approach. However, we should consider avoiding this habit.
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
// Exception is now (being) handled - set the HTTP error status code and prevent caching! Otherwise you'll get an HTTP 200 status code and running the risc of the browser caching the result.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; // Consider using more error status codes depending on the type of exception
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Call the overrided method
base.OnException(filterContext);
}
/// <summary>
/// Does anybody know a better way to obtain the controller action method info?
/// See http://stackoverflow.com/questions/2770303/how-to-find-in-which-controller-action-an-error-occurred.
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
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); }, function(data) { alert('Error: ' + data.message); });
/// </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);
मैं इन सब से क्या प्राप्त करूं? अंतिम परिणाम यह है कि
- मेरे नियंत्रक कार्यों में से कोई भी हैंडलरर एट्रिब्यूट्स पर आवश्यकताएं नहीं हैं।
- मेरे नियंत्रक कार्यों में से कोई भी दोहराव वाले बॉयलर प्लेट त्रुटि कोड को संभालने में शामिल नहीं है।
- मेरे पास त्रुटि हैंडलिंग कोड का एक बिंदु है जो मुझे आसानी से लॉगिंग और अन्य त्रुटियों से संबंधित सामग्री को संभालने की अनुमति देता है।
- एक साधारण आवश्यकता: 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);
टिप्पणियाँ बहुत स्वागत है! मैं शायद कुछ दिन इस समाधान के बारे में ब्लॉग होगा ...
कोई त्रुटि कोड आपको लगता है कि अगर कोई अमान्य डेटा प्रदान करता है तो मुझे वापस लौटना चाहिए, जैसे एक पूर्णांक की आवश्यकता होती है? या एक अवैध ईमेल पता? – thatismatt
500 रेंज में कुछ, समान सर्वर साइड कोड त्रुटि – annakata
जैसा कि 500 रेंज एक सर्वर त्रुटि है, लेकिन सर्वर पर कुछ भी गलत नहीं हुआ है। उन्होंने एक बुरा अनुरोध किया, तो क्या यह 400 रेंज में नहीं होना चाहिए? – thatismatt