UpdatePanel异常处理

17

在我正在构建的ASP.NET Web应用程序中,UpdatePanels中发生异常会导致页面出现JavaScript错误,并在警报中提供一些高级别的错误输出。这对于开发来说还可以接受,但是一旦系统投入生产,显然由于多种原因而不好。我可以使用Try Catch等将麻烦的活动包围起来以控制JavaScript错误,但在某些情况下,我想在主页面上执行操作等以支持用户体验。

如何优雅地处理UpdatePanels中发生的错误,以提供无缝和无JavaScript错误的实现?

3个回答

23
您可以结合ScriptManager的AsyncPostBackError事件(服务器端)和PageRequestManager的EndRequest事件(客户端)来完全处理UpdatePanel使用时出现的服务器端错误。
以下是几个资源,可能会对您有所帮助:
- 自定义ASP.NET UpdatePanel控件的错误处理 - ASP.NET UpdatePanel的错误处理定制 这里有一个简单的示例:
// Server-side
protected void ScriptManager1_AsyncPostBackError(object sender, 
    AsyncPostBackErrorEventArgs e)  {
    ScriptManager1.AsyncPostBackErrorMessage =
        "An error occurred during the request: " +
        e.Exception.Message; 
}


// Client-side
<script type="text/javascript">
  function pageLoad()  {
    Sys.WebForms.PageRequestManager.getInstance().
        add_endRequest(onEndRequest);  
  }

  function onEndRequest(sender, args)  {
    var lbl = document.getElementById("Label1");
    lbl.innerHTML = args.get_error().message;
    args.set_errorHandled(true);
  }
</script>

在我解决了另一个相关问题之后,这个工作得非常好:https://dev59.com/L0rSa4cB1Zd3GeqPTyAT - Michael Adamission

11
如果您只是想修复浏览器JavaScript错误并向用户显示异常消息,则只需在表单声明后的Masterpage中的任何位置添加以下内容即可:
<!-- This script must be placed after the form declaration -->
<script type="text/javascript">
    Sys.Application.add_load(AppLoad);

    function AppLoad() {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
    }

    function EndRequest(sender, args) {
        // Check to see if there's an error on this request.
        if (args.get_error() != undefined) {

            var msg = args.get_error().message.replace("Sys.WebForms.PageRequestManagerServerErrorException: ", "");

            // Show the custom error. 
            // Here you can be creative and do whatever you want
            // with the exception (i.e. call a modalpopup and show 
            // a nicer error window). I will simply use 'alert'
            alert(msg);

            // Let the framework know that the error is handled, 
            //  so it doesn't throw the JavaScript alert.
            args.set_errorHandled(true);
        }
    }
</script>

除非您想自定义消息,否则不需要捕获OnAsyncPostBackError事件。如果您需要更多信息,请访问我的博客文章。


工作了!非常感谢! - Nick DeVore

0

你能否覆盖页面级别的错误方法,捕获异常并处理它们以符合你的需求。

protected override void OnError(EventArgs e)
{
    //show error message here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接