2016-03-18 35 views
0

我想拋出ajax調用客戶端的異常,但我沒有狀態代碼。 我會怎樣處理ajax錯誤函數的錯誤。無法拋出從控制器的AJAX調用異常

當我調用ajax函數時,它會在SaveAccount控制器上生成一些異常,我通過HandleExceptionAttribute處理它,並且我最終返回json,但它碰到了成功函數insted error。 請幫忙。由於

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);  
 

 
       } 
 
      });

回答

1

由於您使用filterContext.ExceptionHandled = true;服務器明白,你已經處理的例外,這就是爲什麼它會返回200狀態。

您可以在filterContext.ExceptionHandled = true;之後添加filterContext.HttpContext.Response.StatusCode = 500;,它應該返回500作爲您的AJAX調用的狀態代碼。