javascript - 为什么 jquery ajax 调用 Controller 没有发现我的异常?

标签 javascript jquery ajax asp.net-mvc

我正在开发一个在我的 asp.net mvc Controller 中调用操作的按钮。我正在 try catch 错误并以适当的方式将它们显示给用户,但我似乎无法弄清楚如何正确地执行此操作。每当我在 Controller 中强制执行异常(出于测试目的)时,我仍然会触发 ajax 调用的 .sucess 部分。这是我的 ajax 调用:

$(document).ready(function() {
    $("#del").on("click", function() {
        var message;
        $.ajax({
            url: "@Url.Action("DeleteImage", "UnitSummary")",
            type: "GET",
            dataType: "json",
            data: { unitId: "@Model.UnitId" },
            error: function(msg) {
                message = msg;
                $('#delsection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + message.statusText + '</div>').fadeIn('slow');
            },
            success: function(msg) {
                message = msg;
                $('#delsection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Image was deleted.</div>').fadeIn('slow');
            }
        });
    });

这是我的 Controller :

[HttpGet]
public ActionResult DeleteImage(int unitId)
{
    try
    {
        throw new Exception("Forced error");
        UnitClient.UpdateUnitImage(unitId, new byte[0]);
    }
    catch (Exception e)
    {
        Log.Error(e);
        return Json(new { e.Message }, JsonRequestBehavior.AllowGet);
    }

    return Json(new JsonResult(), JsonRequestBehavior.AllowGet);
}

成功总是被调用,即使图像没有被删除。我在这里缺少什么?

最佳答案

Whenever I force an exception (for testing purposes) in my controller, the .sucess part of my ajax call i still fired.

下面这行代码不是 jQuery 的 ajax 解释为来自服务器的错误响应的异常(因此没有调用 error 回调), 但是一个常规的 200 OK 响应:

return Json(new { e.Message }, JsonRequestBehavior.AllowGet);

改为这样做:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);

这就是 HTTP 状态代码发挥作用的地方,BadRequest 是一个 HTTP 错误状态代码。

这里是关于BadRequest的更多信息:

Equivalent to HTTP status 400. BadRequest indicates that the request could not be understood by the server. BadRequest is sent when no other error is applicable, or if the exact error is unknown or does not have its own error code.

关于javascript - 为什么 jquery ajax 调用 Controller 没有发现我的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808772/

相关文章:

javascript - 比较数组(不修改原始数组)

javascript - 使用 jQuery Mobile 时警报导航到主页

php - 复选框和检查Datatable Jquery PHP Mysql中的所有功能

javascript - 在主干路由中包含根

ruby-on-rails - Rails ActionController::UnknownFormat 错误与 respond_to

javascript - Ol3 功能的唯一标识符

javascript - 对这个简单的递归函数如何工作感到非常困惑 - 如何解释它?

javascript - 如何在 KnockoutJS 或 JavaScript 中将数字元素格式化为货币

jquery加载方法

javascript - 为什么文档就绪不适用于剑道控件