我可以将自定义错误从JsonResult返回到jQuery ajax错误方法吗?

我可以将自定义错误从JsonResult返回到jQuery ajax错误方法吗?,第1张

我可以将自定义错误从JsonResult返回到jQuery ajax错误方法吗?

您可以编写一个自定义错误过滤器:

public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter{    public void onException(ExceptionContext filterContext)    {        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())        { filterContext.HttpContext.Response.StatusCode = 500; filterContext.ExceptionHandled = true; filterContext.Result = new JsonResult {     Data = new     {         // obviously here you could include whatever information you want about the exception         // for example if you have some custom exceptions you could test         // the type of the actual exception and extract additional data         // For the sake of simplicity let's suppose that we want to         // send only the exception message to the client         errorMessage = filterContext.Exception.Message     },     JsonRequestBehavior = JsonRequestBehavior.AllowGet };        }    }}

然后将其注册为全局过滤器,或者仅应用于您打算用AJAX调用的特定控制器/动作。

在客户端上:

$.ajax({    type: "POST",    url: "@Url.Action("DoStuff", "My")",    data: { argString: "arg string" },    dataType: "json",    traditional: true,    success: function(data) {        //Success handling    },    error: function(xhr) {        try { // a try/catch is recommended as the error handler // could occur in many events and there might not be // a JSON response from the server var json = $.parseJSON(xhr.responseText); alert(json.errorMessage);        } catch(e) {  alert('something bad happened');        }    }});

显然,您可能很快就无聊为每个AJAX请求编写重复的错误处理代码,因此最好为页面上的所有AJAX请求编写一次:

$(document).ajaxError(function (evt, xhr) {    try {        var json = $.parseJSON(xhr.responseText);        alert(json.errorMessage);    } catch (e) {         alert('something bad happened');    }});

然后:

$.ajax({    type: "POST",    url: "@Url.Action("DoStuff", "My")",    data: { argString: "arg string" },    dataType: "json",    traditional: true,    success: function(data) {        //Success handling    }});

另一种可能性是改编[我介绍的全局异常处理程序,以便在ErrorController内检查它是否是AJAX请求,并简单地将异常详细信息作为JSON返回。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4916404.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存