In Visual Studio 2008 if you create a new "Ajax 1.0 Enabled ASP.NET 2.0 Web Application" and paste the following code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="foo" Text="click me" onclick="foo_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
code behind
protected void foo_Click(object sender, EventArgs e) {
throw new Exception("hello");
}
and then click the button, you'll see a javascript alert that says "hello". If you create a .NET 3.5 Web Application and paste the same code in, no alert shows up anymore. What am I missing?
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>
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.