【问题标题】:Unable to throw exception on ajax call from controller无法从控制器调用 ajax 时抛出异常
【发布时间】:2016-03-18 14:00:07
【问题描述】:

我想在 ajax 调用时在客户端抛出异常,但我没有状态码。 我如何处理 ajax 错误函数的错误。

当我调用 ajax 函数时,它会在 SaveAccount 控制器上生成一些异常,然后我通过 HandleExceptionAttribute 处理它,最后我返回 json 但它遇到了错误的成功函数,这是什么问题。 请帮忙。谢谢

public class HandleExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                }
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}

[HandleExceptionAttribute]
    [AllowAnonymous]
    [HttpPost]
    public ActionResult SaveAccount(AccountViewModel vm)
    {
        try
        {
            using (var context = new AdvisorFinancialEntities())
            {
                ..........
                context.SaveChanges();
            }

        }
        catch (Exception ex)
        {
            Exception e = new Exception("Failed to save account");
            e.Data.Add("Accounts", "SaveAccount");

            throw e;
        }
        return Json(true, JsonRequestBehavior.AllowGet);
    }

 $.ajax({
                url: '@Url.Action("SaveAccount", "Accounts")',
                cache: false,
                type: 'POST',
                contentType: 'application/json',
                data: jsonData,
                success: function (result) {
                    ShowToastMessage("Account has been saved successfully", "Success",true);      
                    Reset();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var err = JSON.parse(xhr.responseText);
                    ShowToastMessage(err.Message, "Save Account",false);      

                }
            });

【问题讨论】:

    标签: jquery ajax asp.net-mvc


    【解决方案1】:

    由于您使用filterContext.ExceptionHandled = true;,服务器知道您已经处理了异常,这就是它返回 200 作为状态的原因。

    您可以在filterContext.ExceptionHandled = true; 之后添加filterContext.HttpContext.Response.StatusCode = 500;,它应该返回 500 作为您的 AJAX 调用的状态码。

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 2022-01-27
      • 2023-02-06
      • 2020-11-11
      • 2014-09-03
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多