【发布时间】:2018-09-04 03:55:23
【问题描述】:
当 java 程序找不到所需的信息时,我想返回适当的错误消息(可能是许多已确定的原因之一)。我的java代码是:
}else{
response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");
response.getWriter().write("Captcha description incorrect.");
}
而ajax是:
$.ajax({
type: "POST",
url: "AccountRecoveryQuestionsView",
cache: false,
data: $(questionForm).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
},
error: function(data) {
$("#accountName").focus();
//$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
$('#ajaxGetUserServletResponse').text(data);
}
});
错误函数被触发;但是,该消息不显示。
我已将代码更改为:
statusCode: {
400: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
$("#accountName").focus();
$('#ajaxGetUserServletResponse').text(errorThrown);
}
},
结果是400,错误,空白。
我已经把ajax改成:
.fail (function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
alert(jqXHR.statusText);
alert(jqXHR.responseText);
$("#accountName").focus();
//$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
//$('#ajaxGetUserServletResponse').text(errorThrown);
$('#ajaxGetUserServletResponse').text(jqXHR.responseText);
});
和警报(jqXHR.responseText);正在返回:
<!doctype html><html lang="en"><head><title>HTTP Status [400] – [Bad Request]</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status [400] – [Bad Request]</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Captcha description not correct</p><p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).</p><hr class="line" /><h3>Apache Tomcat/8.5.15</h3></body></html>
我如何才能收到错误消息“验证码描述不正确”。这包含在上面。
【问题讨论】:
-
SC_BAD_REQUEST是400你应该这样做:$.ajax({ statusCode: { 400: function() { //do something } } }); -
关于
#sendError:“如果响应已经被提交,则该方法抛出IllegalStateException。使用该方法后,应认为响应已提交,不应该写给。” -
谢谢@Aniket Sahrawat。这行得通。有没有办法为每个异常返回不同的错误消息,因为我可能会发生大约五种不同的异常(例如,验证码名称不正确、问题未正确回答、电子邮件地址未存档)。
-
如果您为它们抛出异常,那么这不是处理客户端错误的正确方法。您只需编写适当的响应代码和消息,并在发生客户端错误时将其发送回客户端。
-
我在做这个 statusCode: { 400: function() {$('#ajaxGetUserServletResponse').text("Captch not correct.");} },