有没有什么方法可以在jQuery AJAX错误消息中显示自定义异常消息作为警告?
例如,如果我想通过Struts by throw new ApplicationException("User name already exists");在服务器端抛出异常,我想在jQuery AJAX错误消息中捕获这条消息("user name already exists")。
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。
我不知道我错在哪里。我能做什么来解决这个问题?
确保将Response.StatusCode设置为200之外的值。使用Response.Write编写异常消息,然后使用…
xhr.responseText
. .在你的javascript。
两年半过去了,这仍然是正确的做法。)我更进一步,返回了我自己的错误JSON对象,它可以处理单个或多个错误,这对于服务器端表单验证非常好。
你能提供代码吗?
@Wilson在这里的其他高评分答案中也显示了这一点。
现在是2014年。JSON主导的时代。所以我使用xhr.responseJSON。:D
xhr。只有在确保设置了元类型(例如。"application / json - type:")。这是我刚遇到的一个问题;responseText已设置- responseJSON未设置。
控制器:
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);
}
});
这不是对问题的"正确"回答,但它肯定显示了对问题的更高层次的解决方案……好了!
我也在做类似的事情。如果一切都是在开发框上完成的,那么它可以很好地工作。如果我尝试从网络上的另一个盒子xhr连接。responseText包含通用错误页面html,而不是我的自定义消息,请参阅stackoverflow.com/questions/3882752/…
我认为你也应该加上回应。StatusCode = 500;行到OnException方法。
我修改了这个—因为我想要500个状态代码,但是在状态描述中有异常消息(而不是"内部服务器错误")—response.StatusCode = (int)HttpStatusCode.InternalServerError;和response.StatusDescription = filterContext.Exception.Message;
使用IIS7和IOS (iPhone / iPad / iPod),我使用了上面的脚本和下面的代码行:responce。TrySkipIisCustomErrors = true;和反应。StatusCode = (int) HttpStatusCode.InternalServerError;
@AlexanderProkofyev响应已经被设置为500,因为它正在执行OnException方法。
在我的实例中,响应没有设置为500(我使用的正是这段代码),因此错误不会被客户端捕获……
我添加了标记代码,这是有效的,谢谢!
如果您正在使用IIS7或更高版本,您可能需要添加:response。TrySkipIisCustomErrors = true;
一个小的吹毛求疵,但是在error: function (request, status, error) {中request实际上应该被命名为response。参数是你得到的响应,而不是你提出的请求。
服务端:
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
}
}
ClientSide:
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
.";
}
}else if(exception=='parsererror'){
message="Error.
Parsing 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
.";
}
$(this).css("display","inline");
$(this).html(message);
});
You need to convert the responseText to JSON. Using JQuery:
jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
因为这是目前唯一正确的答案!您可以调用"jsonValue"。获取异常消息。
实际上,这不是正确的答案,因为问题没有询问JSON,而示例请求特别要求HTML作为响应。
+ 1正确。注意,通常通过jqXHR发送JSON编码的对象。responseText(字符串)。然后,您可以根据需要使用jsonValue对象。使用Firebug控制台使用console.log(jsonValue)检查响应。
这就得到了"Uncaught SyntaxError: Unexpected number"
通过jqXHR对象的responseJSON属性可以使用解析后的JSON对象。因此不需要解析responseText属性。你只需要做:控制台。日志(jqXHR.responseJSON.Message)
如果调用asp.net,这将返回错误消息标题:
我没有亲自编写formatErrorMessage的所有内容,但是我发现它非常有用。
function formatErrorMessage(jqXHR, exception) {
if (jqXHR.status === 0) {
return ('Not connected.
Please verify your network connection.');
} else if (jqXHR.status == 404) {
return ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
return ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
return ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
return ('Time out error.');
} else if (exception === 'abort') {
return ('Ajax request aborted.');
} else {
return ('Uncaught Error.
' + jqXHR.responseText);
}
}
var jqxhr = $.post(addresshere, function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) {
var responseTitle= $(xhr.responseText).filter('title').get(0);
alert($(responseTitle).text() +"
" + formatErrorMessage(xhr, err) );
})
这就是我所做的,到目前为止它在MVC 5应用程序中是有效的。
控制器的返回类型是ContentResult。
public ContentResult DoSomething()
{
if(somethingIsTrue)
{
Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
Response.Write("My Message");
return new ContentResult();
}
//Do something in here//
string json ="whatever json goes here";
return new ContentResult{Content = json, ContentType ="application/json
If someone is here as in 2016 for the answer, use .fail() for error handling as .error() is deprecated as of jQuery 3.0
[cc]$.ajax("example.php" )
.done(function() {
alert("success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
//handle error here
})
希望对大家有所帮助
jqXHR.error()在jQuery 3.0中被弃用(实际上被删除了),但据我所知,对$.ajax()的error和success回调函数并没有被弃用。
一般/可重用的解决方案
这个答案为以后遇到这个问题的人提供了参考。解决方案包括两件事:当服务器上的验证失败时抛出的自定义异常ModelStateException(当我们使用数据注释和强类型控制器动作参数时,模型状态报告验证错误)自定义控制器操作错误过滤器HandleModelStateExceptionAttribute,它捕获自定义异常并返回HTTP错误状态和主体中的模型状态错误
这为jQuery Ajax调用提供了最佳的基础设施,以便使用success和error处理程序充分发挥它们的潜力。
客户端代码
$.ajax({
type:"POST",
url:"some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
服务器端代码
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
在这篇博客文章中详细介绍了整个问题,您可以在其中找到在您的应用程序中运行它的所有代码。
我发现这很好,因为我可以解析出我从服务器发送的消息,并向用户显示友好的消息,而不需要stacktrace…
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message:" + r.Message);
alert("StackTrace:" + r.StackTrace);
alert("ExceptionType:" + r.ExceptionType);
}
这可能是由于JSON字段名没有引号造成的。
将JSON结构从:
{welcome:"Welcome
- 这应该无关紧要,除非键是JS中的保留字。我不认为这是问题所在。
- JSON.stringify({欢迎:"欢迎"})- - >{"欢迎":"欢迎"}
[cc] error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
在代码错误中,ajax请求捕获客户机到服务器之间的错误连接如果要显示应用程序的错误消息,请在成功范围内发送
如
success: function(data){
// data is object send form server
// property of data
// status type boolean
// msg type string
// result type string
if(data.status){ // true not error
$('#api_text').val(data.result);
}
else
{
$('#error_text').val(data.msg);
}
}
我相信Ajax响应处理程序使用HTTP状态代码来检查是否有错误。
因此,如果您只是在服务器端代码上抛出一个Java异常,但是HTTP响应没有500个状态代码jQuery(或者在本例中可能是XMLHttpRequest对象),那么它只会假定一切正常。
我这样说是因为我在ASP中遇到过类似的问题。我抛出了一个ArgumentException之类的东西("不知道该做什么……"),但是错误处理程序没有触发。
然后,无论是否有错误,我都将Response.StatusCode设置为500或200。
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); }
});
在xhr对象中抛出异常的JSON对象。只使用
alert(xhr.responseJSON.Message);
JSON对象公开了另外两个属性:"ExceptionType"和"StackTrace"
$("#save").click(function(){
$("#save").ajaxError(function(event,xhr,settings,error){
$(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
});
});
使用以下命令在服务器上抛出一个新的异常:
响应。StatusCode = 500
响应。StatusDescription = ex.Message ()
我相信StatusDescription会返回给Ajax调用…
例子:
Try
Dim file As String = Request.QueryString("file")
If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")
Dim sTmpFolder As String ="Temp" & Session.SessionID.ToString()
sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)
file = IO.Path.Combine(sTmpFolder, file)
If IO.File.Exists(file) Then
IO.File.Delete(file)
End If
Catch ex As Exception
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
End Try
Although it has been many years since this question is asked, I still don't find xhr.responseText as the answer I was looking for. It returned me string in the following format:
"{"error":true,"message":"The user name or password is incorrect
< pre > $ (" # fmlogin")。submit(函数(){$ (" # fmlogin") .ajaxError(函数(事件、xhr设置,错误){$(" #加载").fadeOut("快");$ (" # showdata") .fadeIn("慢");$ (" # showdata")。html('错误,请稍后重试或重新加载页面。原因:' + xhr.status ');setTimeout(函数(){$ (" # showdata") .fadeOut({"不透明度":"0 n
这个函数基本上生成唯一的随机API键,如果没有生成,则弹出带有错误消息的对话框
在页面视图:
[cc]Re-Generate
$(document).ready(function(){
$('.changeKey1').click(function(){
debugger;
$.ajax({
url :"index.php?route=account/apiaccess/regenerate",
type :'POST',
dataType:"json",
async:false,
contentType:"application/json; charset=utf-8",
success: function(data){
var result = data.sync_id.toUpperCase();
if(result){
$('#api_text').val(result);
}
debugger;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError +"
" + xhr.statusText +"
" + xhr.responseText);
}
});
});
});
从控制器:
public function regenerate(){
$json = array();
$api_key = substr(md5(rand(0,100).microtime()), 0, 12);
$json['sync_id'] = $api_key;
$json['message'] = 'Successfully API Generated';
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
可选回调参数指定在load()方法完成时要运行的回调函数。回调函数可以有不同的参数:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
如果请求失败,将调用的函数。该函数接收三个参数:jqXHR(在jQuery 1.4中)。对象,描述发生的错误类型的字符串,如果发生了异常,则为可选异常对象。第二个参数(除了null)的可能值是"timeout"、"error"、"abort"和"parsererror"。当HTTP错误发生时,errorthrow接收HTTP状态的文本部分,例如"未找到"或"内部服务器错误"。从jQuery 1.5开始,错误设置可以接受一个函数数组。每个函数将依次调用。注意:跨域脚本和跨域JSONP请求不调用此处理程序。
首先,我们需要在web.config中设置:
****
除了jquery级别的错误部分,你还需要解析包含异常的错误响应,比如:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
然后使用r。您可以实际显示异常文本。
检查完整的代码:http://www.codegateway.com/2012/04/jquery-ajax-hand-exception -throw -by.html