在我正在构建的ASP.NET Web应用程序中,UpdatePanels中发生异常会导致页面出现JavaScript错误,并在警报中提供一些高级别的错误输出。这对于开发来说还可以接受,但是一旦系统投入生产,显然由于多种原因而不好。我可以使用Try Catch等将麻烦的活动包围起来以控制JavaScript错误,但在某些情况下,我想在主页面上执行操作等以支持用户体验。
如何优雅地处理UpdatePanels中发生的错误,以提供无缝和无JavaScript错误的实现?
在我正在构建的ASP.NET Web应用程序中,UpdatePanels中发生异常会导致页面出现JavaScript错误,并在警报中提供一些高级别的错误输出。这对于开发来说还可以接受,但是一旦系统投入生产,显然由于多种原因而不好。我可以使用Try Catch等将麻烦的活动包围起来以控制JavaScript错误,但在某些情况下,我想在主页面上执行操作等以支持用户体验。
如何优雅地处理UpdatePanels中发生的错误,以提供无缝和无JavaScript错误的实现?
// 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>
<!-- 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事件。如果您需要更多信息,请访问我的博客文章。
你能否覆盖页面级别的错误方法,捕获异常并处理它们以符合你的需求。
protected override void OnError(EventArgs e)
{
//show error message here
}