i see that i get a big html text when i return a HttpException() from an ajax call.
我看到当我从ajax调用返回HttpException()时,我得到一个大的html文本。
if i do something like this in my controller:
如果我在我的控制器中做这样的事情:
if (errors.Count > 0)
{
throw new HttpException(404, "This is my custom error msg");
}
i want a nice simple way to parse out that Error Message on the javascript side. Right now when i look at the callback on the client side with something like this
我想要一个简单的方法来解析javascript端的错误消息。现在,当我用这样的东西看客户端的回调时
function decodeErrorMessage(jqXHR, textStatus, errorThrown) {
i see that jqxHR = "3", textStatus = a very long html doc (with a a call stack and error message and errorThrown is "error"
我看到jqxHR =“3”,textStatus =一个非常长的html doc(带有调用堆栈和错误消息,errorThrown是“错误”
what is the best way to simply pass back and show an error from an http exception?
简单传回并从http异常中显示错误的最佳方法是什么?
1 个解决方案
#1
5
Instead of throwing the exception in the controller, catch it and set the response code for the AJAX response:
而不是在控制器中抛出异常,捕获它并设置AJAX响应的响应代码:
View logic setup with JQuery:
使用JQuery查看逻辑设置:
$("#btnRefresh").live("click", function(e) {
$.ajax({
type: "POST",
url: '@Href("~/Home/Refresh")',
data: "reportId=@Model.Id"
})
.done(function(message) {
alert(message);
})
.fail(function(serverResponse) {
alert("Error occurred while processing request: " + serverResponse.responseText);
});
e.preventDefault();
});
Then in your Controller code you catch the exception instead of throwing it:
然后在您的Controller代码中捕获异常而不是抛出异常:
[HttpPost, VerifyReportAccess]
public ActionResult Refresh(Guid reportId)
{
string message;
try
{
message = _publisher.RequestRefresh(reportId);
}
catch(Exception ex)
{
HttpContext.Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
message = ex.Message;
}
return Json(message);
}
#1
5
Instead of throwing the exception in the controller, catch it and set the response code for the AJAX response:
而不是在控制器中抛出异常,捕获它并设置AJAX响应的响应代码:
View logic setup with JQuery:
使用JQuery查看逻辑设置:
$("#btnRefresh").live("click", function(e) {
$.ajax({
type: "POST",
url: '@Href("~/Home/Refresh")',
data: "reportId=@Model.Id"
})
.done(function(message) {
alert(message);
})
.fail(function(serverResponse) {
alert("Error occurred while processing request: " + serverResponse.responseText);
});
e.preventDefault();
});
Then in your Controller code you catch the exception instead of throwing it:
然后在您的Controller代码中捕获异常而不是抛出异常:
[HttpPost, VerifyReportAccess]
public ActionResult Refresh(Guid reportId)
{
string message;
try
{
message = _publisher.RequestRefresh(reportId);
}
catch(Exception ex)
{
HttpContext.Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
message = ex.Message;
}
return Json(message);
}