有什么方法可以在jQueryAJAX错误消息中显示自定义异常消息作为警报吗?
例如,如果我想通过抛出新的ApplicationException(“用户名已经存在”),通过Struts在服务器端抛出异常;,我想在jQueryAJAX错误消息中捕获此消息(“用户名已存在”)。
jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
在错误回调中的第二个警报中,我向thrownError发出警报,我得到了未定义,xhr.status代码为500。
我不知道我错在哪里。我可以做什么来解决这个问题?
控制器:
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
[ClientErrorHandler]
public class SomeController : Controller
{
[HttpPost]
public ActionResult SomeAction()
{
throw new Exception("Error message");
}
}
查看脚本:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
首先,我们需要在web.config中设置<serviceDebug includeExceptionDetailInFaults=“True”/>:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
**<serviceDebug includeExceptionDetailInFaults="true" />**
</behavior>
</serviceBehaviors>
除了jquery级别的错误部分,您还需要解析包含异常的错误响应,如:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
然后使用r.Message,您可以实际显示异常文本。
检查完整代码:http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html
服务器端:
doPost(HttpServletRequest request, HttpServletResponse response){
try{ //logic
}catch(ApplicationException exception){
response.setStatus(400);
response.getWriter().write(exception.getMessage());
//just added semicolon to end of line
}
}
客户端:
jQuery.ajax({// just showing error property
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
}
});
一般Ajax错误处理
如果我需要对所有ajax请求进行一些通用错误处理。我将设置ajaxError处理程序,并在html内容顶部名为errorcontainer的div上显示错误。
$("div#errorcontainer")
.ajaxError(
function(e, x, settings, exception) {
var message;
var statusErrorMap = {
'400' : "Server understood the request, but request content was invalid.",
'401' : "Unauthorized access.",
'403' : "Forbidden resource can't be accessed.",
'500' : "Internal server error.",
'503' : "Service unavailable."
};
if (x.status) {
message =statusErrorMap[x.status];
if(!message){
message="Unknown Error \n.";
}
}else if(exception=='parsererror'){
message="Error.\nParsing JSON Request failed.";
}else if(exception=='timeout'){
message="Request Time out.";
}else if(exception=='abort'){
message="Request was aborted by the server";
}else {
message="Unknown Error \n.";
}
$(this).css("display","inline");
$(this).html(message);
});
jQuery.parseJSON对于成功和错误都很有用。
$.ajax({
url: "controller/action",
type: 'POST',
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
notify(data.toString());
notify(textStatus.toString());
},
error: function (data, textStatus, jqXHR) { notify(textStatus); }
});