在我正在构建的ASP.NET web应用程序中实现的UpdatePanels中发生异常时,它们会在页面上导致JavaScript错误,并在警报中显示一些高级错误输出。这是用于开发的OKish,但是一旦系统投入生产,由于多种原因,它显然是不好的。我可以用Try Catch等围绕着麻烦的活动来控制Javascript错误,但在某些情况下,我想在主页上采取行动等,以支持用户体验。
如何优雅地处理UpdatePanels中出现的错误,以提供无缝且无错误的Javascript实现?
发布于 2009-12-01 23:55:14
在使用UpdatePanel时,您可以结合使用ScriptManager (服务器端)上的AsyncPostBackError事件和PageRequestManager (客户端)上的EndRequest事件来完全处理服务器端错误。
这里有几个对你有帮助的资源:
Customizing Error Handling for ASP.NET UpdatePanel Controls
Error Handling Customization for 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>
发布于 2010-01-20 09:47:45
如果您只想修复浏览器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。Go to my blog post if you want more information about this.
发布于 2009-12-01 20:56:10
你能重写页面级错误方法,捕捉异常并处理你认为合适的方式吗?
protected override void OnError(EventArgs e)
{
//show error message here
}
https://stackoverflow.com/questions/1826008
复制相似问题