【问题标题】:Page_Error does not show Unhandled Exception in WebMethod call by JavascriptPage_Error 在 Javascript 调用的 WebMethod 中不显示未处理的异常
【发布时间】:2017-03-25 11:02:21
【问题描述】:

我是 C# ASP.net 的新手。我在 Ubuntu 中使用 Monodevelop 创建一个简单的 WebForm。

默认.aspx.cs:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Error(object sender, EventArgs e)
    {
            Exception Ex = Server.GetLastError();
            Console.WriteLine(Ex.Message);
    }


    [System.Web.Services.WebMethod]
    public static string TestUnhandledException()
    {
        throw new Exception("abc");
    }
}

默认.aspx

<%@ Page Language="C#" Inherits="MyFirstWebForm.Default" %>
<!DOCTYPE html>
<html>

<head runat="server">
    <title>Default</title>
    <script>
        function Test() {
            PageMethods.TestUnhandledException(OnSuccessCallback, OnFailureCallback);
        }

        function OnSuccessCallback(res) {}
        function OnFailureCallback() {}
    </script>

</head>

<body>
    <form id='form1' runat='server'>
        <asp:scriptmanager enablepagemethods="true" id="scpt" runat="server"> </asp:scriptmanager>
        <asp:button id="Button1" runat="server" text="Initialize" OnClientClick='Test();return false;'/>
    </form>

</body>
</html>

TestUnhandledException() 方法工作正常,但在我调试时,没有显示异常消息并且 Page_Error() 永远不会运行。

我错过了什么吗?我应该如何在 ASP.NET webform 中记录未处理的异常?感谢您的帮助。

更新:Page_Load 抛出的异常被 Page_Error 捕获,但 [WebMethod] 抛出的异常没有。

【问题讨论】:

    标签: c# asp.net exception-handling webforms


    【解决方案1】:

    看来捕捉WebMethod抛出的未处理异常并不简单。 来自这个post

    您不能只在 Global.aspx.cs 文件中添加几行代码 记录未处理异常的 Application_Error 事件处理程序方法 因为 ASP.NET Web 服务管道绕过了这个事件,所以它 可以将所有异常返回给调用者。

    所以可能最简单的方法是用 try-catch 块包围方法,如帖子所示

    【讨论】:

      【解决方案2】:

      你检查过内部异常吗?你的异常信息应该在那里

      【讨论】:

      • 问题出在我调试时,Page_Error() 从一开始就不会运行
      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 2015-08-14
      • 2010-12-26
      • 1970-01-01
      • 2020-11-11
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多