【发布时间】: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