2014-10-02 31 views
0

我在jQuery中調用的aspx頁面上有一個WebMethod,我試圖讓它在彈出框中顯示拋出異常的消息,而不是在錯誤函數下運行代碼,調試器停止說「用戶未處理的異常」。我如何將錯誤返回給客戶端?jquery AJAX調用web方法不運行錯誤函數

[WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public static void SubmitSections(string item) 
    { 
     try 
     { 
      throw new Exception("Hello"); 
     } 

     catch (Exception ex) 
     { 
      HttpContext.Current.Response.Write(ex.Message); 
      throw new Exception(ex.Message, ex.InnerException); 
     } 
    } 

在我的js文件:

$.ajax({ 
    type: "POST", 
    url: loc + "/SubmitSections", 
    data: dataValue, 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    success: function (Result) { 
     $("#modal-submitting").modal('hide'); 
     document.location = nextPage; 
    }, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
     $("#modal-submitting").modal('hide'); 
     alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown); 
    } 
});//ajax call end 

回答

0

你應該返回一個錯誤,例如HTTP狀態代碼500,在客戶端被處理爲錯誤。

拋出服務器端的錯誤沒有被返回給客戶端。

對於WebMethod,您應該設置Response.StatusCode。

HttpContext.Current.Response.StatusCode = 500; 
+0

好的,我明白了。當你說返回一個錯誤,你的意思是返回一個字符串,其中的錯誤信息?我怎樣才能得到錯誤:function()來執行? – KateMak 2014-10-02 22:06:05

+0

@KateMak返回新的HttpStatusCodeResult(errorCode,「Message」);如果你願意,errorCode可以是500。 – 2014-10-02 22:11:37

+0

這沒有達到預期的效果... – KateMak 2014-10-02 22:15:11

0

我覺得你的問題是,你正在做從客戶端腳本JSON請求,但你的catch塊只是寫文成反應,而不是JSON,所以客戶端錯誤功能不火。

嘗試使用諸如Newtonsoft.Json之類的庫將.NET類轉換爲JSON響應。然後,您可以創建一些簡單的包裝類來表示響應數據,如: -

[Serializable] 
public class ResponseCustomer 
{ 
    public int ID; 
    public string CustomerName; 
} 

[Serializable] 
public class ResponseError 
{ 
    public int ErrorCode; 
    public string ErrorMessage; 
} 

,並在你的catch塊..

var json = JsonConvert.SerializeObject(new ResponseError 
              { 
               ErrorCode = 500, 
               ErrorMessage = "oh no !" 
              }); 
context.Response.Write(json); 

順便說一句:throw new Exception(...)不推薦的做法,因爲您將失去堆棧跟蹤,這對調試或日誌記錄沒有幫助。如果您需要重新拋出異常,推薦使用throw;(無參數)。