【发布时间】:2012-03-07 02:16:24
【问题描述】:
如何将自定义错误信息从 ASP.NET MVC3 JsonResult 方法传递到 jQuery.ajax() 的 error(或 success 或 complete,如果需要)函数?理想情况下,我希望能够:
- 仍然在服务器上抛出错误(这是用于记录的)
- 检索有关客户端错误的自定义信息
这是我的代码的基本版本:
控制器 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 -
xhr.getResponseHeader()等包含默认的ASP.NET错误页面,但没有我的信息 - 我认为这可能是可能的,但我做错了吗?
- 然后在 jQuery 错误处理程序中检查
【问题讨论】:
标签: ajax asp.net-mvc-3 jquery