jQuery Ajax 错误处理,显示自定义异常消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/377644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Ajax error handling, show custom exception messages
提问by
Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
有什么方法可以在我的 jQuery AJAX 错误消息中将自定义异常消息显示为警报?
For example, if I want to throw an exception on the server side via Strutsby throw new ApplicationException("User name already exists");
, I want to catch this message ('user name already exists') in the jQuery AJAX error message.
例如,如果我想通过Strutsby在服务器端抛出异常throw new ApplicationException("User name already exists");
,我想在 jQuery AJAX 错误消息中捕获此消息(“用户名已存在”)。
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);
}
});
}
});
On the second alert, where I alert the thrown error, I am getting undefined
and the status code is 500.
在我警告抛出的错误的第二个警报中,我收到undefined
并且状态代码为 500。
I am not sure where I am going wrong. What can I do to fix this problem?
我不确定我哪里出错了。我能做些什么来解决这个问题?
回答by Sprintstar
Make sure you're setting Response.StatusCode
to something other than 200. Write your exception's message using Response.Write
, then use...
确保您设置的Response.StatusCode
不是 200。使用 编写异常消息Response.Write
,然后使用...
xhr.responseText
..in your javascript.
..在你的javascript中。
回答by AlexMAS
Controller:
控制器:
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");
}
}
View script:
查看脚本:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
回答by Sanjeev Kumar Dangi
ServerSide:
服务器端:
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");
}
}
});
Generic Ajax Error Handling
通用 Ajax 错误处理
If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.
如果我需要为所有 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);
});
回答by Sydney
You need to convert the responseText
to JSON. Using JQuery:
您需要将 转换responseText
为 JSON。使用 JQuery:
jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
回答by Sam Jones
If making a call to asp.net, this will return the error message title:
如果调用 asp.net,这将返回错误消息标题:
I didn't write all of formatErrorMessage myself but i find it very useful.
我没有自己写所有的 formatErrorMessage 但我发现它非常有用。
function formatErrorMessage(jqXHR, exception) {
if (jqXHR.status === 0) {
return ('Not connected.\nPlease 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.\n' + 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() + "\n" + formatErrorMessage(xhr, err) );
})
回答by Cengiz Araz
This is what I did and it works so far in a MVC 5 application.
这就是我所做的,到目前为止它在 MVC 5 应用程序中有效。
Controller's return type is ContentResult.
控制器的返回类型是 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"};
}
And on client side this is what ajax function looks like
在客户端,这就是 ajax 函数的样子
$.ajax({
type: "POST",
url: URL,
data: DATA,
dataType: "json",
success: function (json) {
//Do something with the returned json object.
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
xhr.status;
//The message added to Response object in Controller can be retrieved as following.
xhr.responseText;
}
});
回答by Learner
If someone is here as in 2016 for the answer, use .fail()
for error handling as .error()
is deprecated as of jQuery 3.0
如果有人像 2016 年一样在这里寻求答案,请使用自 jQuery 3.0 起已弃用的.fail()
错误处理.error()
$.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
//handle error here
})
I hope it helps
我希望它有帮助
回答by Robert Koritnik
A general/reusable solution
通用/可重用的解决方案
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
提供此答案以供将来遇到此问题的所有人员参考。解决方案包括两件事:
- Custom exception
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters) - Custom controller action error filter
HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the body
ModelStateException
在服务器上验证失败时抛出的自定义异常(当我们使用数据注释和使用强类型控制器操作参数时,模型状态报告验证错误)- 自定义控制器操作错误过滤器
HandleModelStateExceptionAttribute
,可捕获自定义异常并返回 HTTP 错误状态,主体中包含模型状态错误
This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success
and error
handlers.
这为 jQuery Ajax 调用提供了最佳基础设施,以充分利用它们success
与error
处理程序的潜力。
Client side code
客户端代码
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
Server side code
服务端代码
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog postwhere you can find all the code to run this in your application.
这篇博文详细介绍了整个问题,您可以在其中找到在您的应用程序中运行它的所有代码。
回答by crazyDiamond
I found this to be nice because I could parse out the message I was sending from the server and display a friendly message to the user without the stacktrace...
我发现这很好,因为我可以解析我从服务器发送的消息,并在没有堆栈跟踪的情况下向用户显示一条友好的消息......
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
回答by Wara Haii
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
such as
如
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);
}
}