2014-10-02 59 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;(无参数)。