2013-10-29 53 views
4

我正在通過AJAX進行ASP.NET MVC調用方法,該錯誤會引發異常。我想把異常的消息傳回客戶端,我寧願不必去捕捉異常。事情是這樣的:ASP.NET MVC Ajax錯誤返回視圖,而不是Ajax

[HttpPost] 
public ActionResult AddUser(User user) { 
    if (UserIsValid(user)) { 
    return Json(new { resultText = "Success!" }); 
    } 
    throw new Exception("The user was invalid. Please fill out the entire form."); 
} 

我看到在我的螢火響應的HTML頁面

<!DOCTYPE html> 
<html> 
    <head> 
     <title>"The user was invalid. Please fill out the entire form."</title> 
     ..... 

我想不會被迫使用try catch塊來做到這一點。有沒有一種方法可以自動獲取jQuery $(document).ajaxError(function(){}來讀取這個異常消息?這是不好的做法嗎?我可以重寫控制器OnException嗎?或者我必須嘗試/ catch並返回?JSON

像這樣的事情將是很好:

$(document).ajaxError(function (data) { 
    alert(data.title);   
}); 
+0

我想你可以使用說明(這裏)的方法(http://stackoverflow.com/questions/4707755/asp- net-mvc-ajax-error-handling)並修飾你的控制器動作方法,該方法返回帶有屬性過濾器的json。 –

回答

0

而不是處理這個由服務器產生的異常,爲什麼沒有一個標誌JSON響應

[HttpPost] 
public ActionResult AddUser(User user) { 
    if (UserIsValid(user)) { 
    return Json(new { success = true, resultText = "Success!" }); 
    } 

    return Json(new { success = false, resultText = "The user was invalid. Please fill out the entire form." }); 
} 
+0

我想在這裏做什麼,但不必有一個if語句。我想讓ASP.NET框架自動處理錯誤,所以我不必每次都寫if/else塊。 –

+0

已更新評論刪除if/else塊並遵循初始方法 –

+0

正確,但這是我已經在做的。我希望ASP.NET框架自動爲我處理此問題,並自動將resultText設置爲異常消息,而無需編寫此代碼。有沒有辦法做到這一點? –

8

你可以使用自定義過濾器來做到這一點:

$(document).ajaxError(function(event, jqxhr) { 
    console.log(jqxhr.responseText); 
}); 

-

[HttpPost] 
[CustomHandleErrorAttribute] 
public JsonResult Foo(bool isTrue) 
{ 
    if (isTrue) 
    { 
     return Json(new { Foo = "Bar" }); 
    } 
    throw new HttpException(404, "Oh noes..."); 
} 

public class CustomHandleErrorAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     var exception = filterContext.Exception; 
     var statusCode = new HttpException(null, exception).GetHttpCode(); 

     filterContext.Result = new JsonResult 
     { 
      JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example 
      Data = new 
      { 
       error = true, 
       message = filterContext.Exception.Message 
      } 
     }; 

     filterContext.ExceptionHandled = true; 
     filterContext.HttpContext.Response.Clear(); 
     filterContext.HttpContext.Response.StatusCode = statusCode; 
     filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
    } 
} 

由我這篇文章有點啓發:http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc