jQueryajax错误处理,显示自定义异常消息。有什么方法可以在jQueryAjax错误消息中显示自定义异常消息作为警报吗?例如,如果我想在服务器端通过支柱通过throw new ApplicationException("User name already exists");,我想在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);
}
});
}});在第二个警报中,当我警告抛出的错误时,我得到undefined状态代码是500。我不知道我哪里出了问题。我能做些什么来解决这个问题?
3 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
Response.StatusCode
Response.Write
xhr.responseText
萧十郎
TA贡献1815条经验 获得超13个赞
服务器端:
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错误处理
$("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); });
芜湖不芜
TA贡献1796条经验 获得超7个赞
主计长:
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); }});
添加回答
举报
0/150
提交
取消