Chr*_*ris 16 asp.net error-handling updatepanel exception asp.net-ajax
在我正在构建的ASP.NET Web应用程序中实现的UpdatePanels中发生异常的情况下,它们会在页面上导致JavaScript错误,并在警报中提供一些高级错误输出.这对于开发来说是可行的,但是一旦系统处于生产状态,由于多种原因显然没有好处.我可以使用Try Catch等来控制Javascript错误,但在某些情况下,我想在主页面上执行操作以支持用户体验.
我如何优雅地处理UpdatePanels中出现的错误,以提供无缝和Javascript无错误的实现?
Rob*_*sor 20
您可以使用上的ScriptManager(服务器端)的AsyncPostBackError事件的组合,并在PageRequestManager(客户端)的EndRequest事件使用的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>
Run Code Online (Sandbox Code Playgroud)
Wag*_*lva 10
If you just want to fix the browser javascript error and display the exception message to the user, you just need to add this to your Masterpage somewhere after the form declaration:
<!-- 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>
Run Code Online (Sandbox Code Playgroud)
You do not need to catch the OnAsyncPostBackError even unless you want to customize the message. Go to my blog post if you want more information about this.
归档时间: |
|
查看次数: |
13611 次 |
最近记录: |