2015-06-08 67 views
0

我想通过JQuery Post和Webmethod抛出一个处理异常,以便我可以将错误消息返回给警报函数。所以这只是一个测试脚本。C#Webmethod + Jquery发布错误消息

我有这个设置,并且正在捕获错误,现在我需要将服务器错误返回到警报函数!

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public static string Test() 
{ 
    try 
    { 
     string value = null; 
     if (value.Length == 0) // <-- Causes exception 
     { 
      Console.WriteLine(value); // <-- Never reached 
     } 

    } 

    catch (Exception E) 
    {    

     StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true); 
     sw.WriteLine(E.Message); 

     sw.Close(); 
     sw.Dispose(); 

     throw new Exception("error"); 

    } 

    return "bla"; 

这我帖子的脚本:

$("#btnTest").click(function() { 
      $.ajax({ 
       type: 'POST', 
       url: "my_test2.aspx/Test", 
       contentType: "application/json; charset=utf-8", 
       success: function (data) { 
        alert('Success!') 
       }, 
       error: function (xhr, status, error) { 
        var exception = JSON.parse(xhr.responseText); 
        alert(exception.Message); 
        // Here I need to return server error 
       } 
      }); 
     }); 

由于P

+0

什么问题? – Mairaj

+0

尝试返回新的异常错误,而不是抛出新的异常错误 –

回答

0

谢谢@你让我走上正轨。解决如下!

throw new HttpException(E.Message); 
1

您需要一个HTTP状态代码做到这一点。

修改代码到这个

catch (Exception E) 
    {    

     StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true); 
     sw.WriteLine(E.Message); 

     sw.Close(); 
     sw.Dispose(); 

     return new HttpStatusCodeResult(500, E.Message); 
    } 

500代表internal server error。如果它更合适,可以寻找另一个。我觉得400 - Bad Request可能更适合你的情况。

+0

什么类型是'HttpStatusCodeResult'?这种类型在哪里找到 –