简体   繁体   English

使用jQuery Ajax时如何在VB.NET中捕获异常

[英]How to catch an exception in VB.NET when using jQuery ajax

I'm using jQuery to handle all my ajax needs for an ASP.NET site coded in VB. 我正在使用jQuery处理以VB编码的ASP.NET网站的所有ajax需求。 When I use the built in $.ajax function to POST to a code-behind function and there is an exception, it simply exits the function, and shows an error on the client side. 当我使用内置的$ .ajax函数将其POST到代码隐藏函数时,出现一个异常,它只是退出该函数,并在客户端显示错误。

Besides making debugging difficult when coding, the bigger issue is that the Application_Error function in Global.asax isn't firing when those exceptions occur. 除了使编码时的调试困难之外,更大的问题是,发生这些异常时,Global.asax中的Application_Error函数不会触发。 This is making it almost impossible to track production errors. 这使得几乎不可能跟踪生产错误。

Why would it not bubble up to Application_Error? 为什么它不会冒泡到Application_Error? Is the answer to wrap the code-behind function in a Catch statement? 将代码隐藏函数包装在Catch语句中的答案是吗?

jQuery ajax function: jQuery ajax函数:

$.ajax({
    type: "POST",
    url: "page.aspx/GetData",
    data: "{'param':'" + param_value + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",

    success: function(msg) {
        processData(msg);
    },

    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error: " + textStatus + " - " + errorThrown);
    }
});

VB.NET function: VB.NET功能:

<Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetData(ByVal param As Integer) As String
    'Parse some data
    Return data
End Function

I figured out a work around. 我想通了。 Although I did not find a way to directly get the error to fire the Application_Error event, I discovered a property on the jQuery XMLHttpRequest object that contains the actual exception text. 尽管我没有找到直接获取引发Application_Error事件的错误的方法,但我在jQuery XMLHttpRequest对象上发现了一个包含实际异常文本的属性。

Here is an example that will show the error in an alert: 这是一个在警报中显示错误的示例:

error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert("Error: " + XMLHttpRequest.responseText);
}

Another idea is to submit the error via AJAX to a web method that will handle all the error event logic. 另一个想法是通过AJAX将错误提交到将处理所有错误事件逻辑的Web方法。

使用.Net 3.5,您可以拉入ScriptManager对象并向其中注册您的javascript,这使.Net可以管理脚本(对于MS Ajax,它不是jsut,它与第三方库一起使用),这可能是一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM