ASP.NET Ajax Error/Exception Handling – the simple way
A lot has been said about error/exception handling with ASP.NET Ajax pages, more specifically, how to properly handle and display error messages inside an UpdatePanel. For instance, Scott Gu wrote this sometime ago:
You can now optionally [...] intercept any error message sent back from the server, and perform custom client-side actions as a result [...]. (source)
Well, I disagree with “optionally”. As far as I understand, if you don’t explicitly intercept the error/exception sent back from the server from within an UpdatePanel, your user will get an unfriendly javascript error like this:
So what can you do to fix this? Easy, just add this piece of Javascript code to your Masterpage (or to any page if you don’t have/use a Masterpage):
<%-- This script must be placed after the form declaration (i.e. <form id="form1" runat="server">) --%>
<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>
Now you should get error messages like this (javascript alert): 
This is exactly how exceptions used to be displayed when thrown inside an UpdatePanel before .NET 3.5.
Note: I do understand the benefits of a the new approach. It gives you flexibility to present the error message any way you want, before your hands where quite tied to this simple Javascript alert window.
As a matter of fact, I’ve implemented a nice ModalPopup and have ensure that only user-friendly messages are actually shown: only messages of a certain type (i.e. UIMessageException) are forwarded to the user without any cleanup/transformation.
References:
- Exception handling best practices in ASP.NET web applications
- How Do I: Customize Error Handling for the ASP.NET AJAX UpdatePanel
- MVP blog: UpdatePanel: having fun with errors
- MSDN post (be careful, not 100% correct): Customizing Error Handling for ASP.NET UpdatePanel Controls
Cheers!
