2011-07-11 246 views
2

如何从webmethod获取错误消息,我想发起错误。另外,我想为不同的场合提供不同的错误信息。从webmethod发送错误消息

 $.ajax({ 
      type: "POST", 
      url: "betting.aspx/submitFunction", 
      data: JSON.stringify({ results: jsonObj, edit: $("#ctl00_ContentPlaceHolder1_CreateOrEdit").val() }), 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(arg) { //call successfull 
       window.location = "bHistory.aspx"; 
      }, 
      error: function(xhr) { 
       alert("Error! You need to login, and try again"); 
       window.location = "login.aspx"; 
       //error occurred 
      } 
     }); 

回答

0

我也遇到过这个问题。问题是,如果你从你的web方法抛出异常,它会被包装,就像这样"Message":"{your message}","StackTrace":" at ...

我最终做的是创建这个js函数来解析返回的异常。
这非常难看,我很想看看有没有人提出更好的方案。

function getErrorMessage(e) { 
    return e.responseText.substring(e.responseText.indexOf("\"Message\":\"") + "\"Message\":\"".length, e.responseText.indexOf("\",\"Stack")); 
} 
+0

谢谢,这正是我所需要的。 – gormit

5

你可以试试这个:

error: function(msg, status) { 
    if (status === "error") { 
     var errorMessage = $.parseJSON(msg.responseText); 
     alert(errorMessage.Message); 
    } 
} 
+0

+1这应该是答案。谢谢。 –

+0

我也是+1。好多了 –