Dre*_*nor 29 ajax jquery asp.net-mvc-3
如何将ASP.NET MVC3 JsonResult方法中的自定义错误信息传递给error(success或者complete,如果需要)函数jQuery.ajax()?理想情况下,我希望能够:
这是我的代码的基本版本:
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);
}
Run Code Online (Sandbox Code Playgroud)
$.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
}
});
Run Code Online (Sandbox Code Playgroud)
我尝试过的事情(没有成功):
catch块
返回错误信息catch块中
编辑HTTP响应xhr在jQuery错误处理程序中检查xhr.getResponseHeader()等包含默认的ASP.NET错误页面,但没有我的信息Dar*_*rov 50
您可以编写自定义错误过滤器:
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
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其注册为全局过滤器或仅应用于您要使用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');
}
}
});
Run Code Online (Sandbox Code Playgroud)
显然,您可能很快就会为每个AJAX请求编写重复的错误处理代码,因此最好为页面上的所有AJAX请求编写一次:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
Run Code Online (Sandbox Code Playgroud)
然后:
$.ajax({
type: "POST",
url: "@Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Run Code Online (Sandbox Code Playgroud)
另一种可能性是调整我提交的全局异常处理程序,以便在ErrorController中检查它是否是一个AJAX请求,并简单地将异常详细信息作为JSON返回.
Art*_*m G 10
上面的建议不适用于远程客户端的IIS.他们将收到一个标准的错误页面,如500.htm,而不是带有消息的响应.您必须在web.config中使用customError模式,或者添加
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
要么
"您也可以进入IIS管理器 - >错误页面然后单击右侧的"编辑功能设置..."并将选项设置为"详细错误",然后它将是您的应用程序处理错误而不是IIS. "
您可以返回带有错误的 JsonResult 并跟踪 javascript 端的状态以显示错误消息:
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37834 次 |
| 最近记录: |