我可以返回自定义错误从JsonResult到jQuery ajax错误方法吗?
发布时间:2020-12-16 19:44:21 所属栏目:百科 来源:网络整理
导读:如何将自定义错误信息从ASP.NET MVC3 JsonResult方法到错误(或成功或完成,如果需要)jQuery.ajax()的函数?理想情况下,我想要能够: 仍然在服务器上抛出错误(这用于日志记录) 在客户端上检索有关错误的自定义信息 这里是我的代码的基本版本: 控制器JsonRes
如何将自定义错误信息从ASP.NET MVC3 JsonResult方法到错误(或成功或完成,如果需要)jQuery.ajax()的函数?理想情况下,我想要能够:
>仍然在服务器上抛出错误(这用于日志记录) 这里是我的代码的基本版本: 控制器JsonResult方法 public JsonResult DoStuff(string argString) { string errorInfo = ""; try { DoOtherStuff(argString); } catch(Exception e) { errorInfo = "Failed to call DoOtherStuff()"; //Edit HTTP Response here to include 'errorInfo' ? throw e; } return Json(true); } JavaScript $.ajax({ type: "POST",url: "../MyController/DoStuff",data: {argString: "arg string"},dataType: "json",traditional: true,success: function(data,statusCode,xhr){ if (data === true) //Success handling else //Error handling here? But error still needs to be thrown on server... },error: function(xhr,errorType,exception) { //Here 'exception' is 'Internal Server Error' //Haven't had luck editing the Response on the server to pass something here } }); 我试过的东西(没有成功): >从catch块中返回错误信息 >这工作,但异常不能抛出 >在catch块中编辑HTTP响应 >然后在jQuery错误处理程序中检查xhr
您可以编写自定义错误过滤器:
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" },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",success: function(data) { //Success handling } }); 另一种可能性是适配a global exception handler I presented,以便在ErrorController内部检查它是否是一个AJAX请求,并简单地返回JSON的异常细节。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |