I have added try catches in my site which work great. The next part in development is to set up some exception handling output. Obviously I don’t want the site to crumble when an error occurs and I don’t want a horrible error screen. So, somewhere in the middle would be nice.
I was thinking to have an exception handler user control in the main master page which wil output a nice little message when something goes wrong.
What would be the best way to pass the exception to this user control? I was thinking of using a session variable.
Does anyone have a solution to this problem?
Thanks
This is easier than you’re making it. Create a page called error.aspx (or whatever you want to call it), and turn the CustomErrors on in the web.config.
There is a lot of configurability to handle different http errors or random exceptions. If you want, you can dump the exception message (or the exception itself) into the session or use the
HttpServerUtility.GetLastError(documentation)and then output any number of different messages on the error page. This will even catch exceptions that you DON’T catch.CustomErrors Documentation
Edit:
@Icarus indicates that OP is looking for a solution by which the page continues to render and output while only showing an error message within the page, so I’ll provide an answer to that as well.
There are a few ways I’ve handled this in the past. For very complex pages where the behavior requested is fatal (the page result can’t be known), I’ve always deferred to an error page as I mentioned above that includes major master elements. So the menu, header, etc are all still there, but the notification of cataclysm is evident.
The behavior you seem to be looking for is something I would use less out of a need to report exceptions than to report general messages. My preference is to have a user control that has a public bindable property that a message can be injected into. Such as (forgive the VB, I can’t seem to find my C# version):
Then the output could be any string message you like or you could program in a number of presets, fetch from resources, whatever. As to how to get it in there, we have taken the MasterPage route. We have a method in our master pages which assigns such a property in the user control directly. In order for this method to be callable, each page that uses the master page has to include the VirtualPath property, otherwise the method will not be available at compile time.
This then allows the
Masterproperty to be called from within the page itself to call this property:Keep in mind that
Me.Masterfrom within the page is not the same asPage.Master. So your exception will either need to bubble up to the actual page or the page reference itself will have to be sent down to your usercontrols as a property.