comb
comb

Reputation: 473

Usercontrol exception handling

I have a scenario where i'm loading a control in the masterpage:

   Control mycontrol = LoadControl("~/mycontrol");
   aspholder.Controls.Add(MyControl);

Now i need to know if it is possible to catch exceptions (even for statment that do not have a try catch( that are thrown in the usercontrol from the master page

Upvotes: 0

Views: 1027

Answers (1)

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

You can handle unhandled exceptions on TemplateControl.Error event. MasterPage,Page,UserControl all of them inherit it, so you can write:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class MyMasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Error += Page_Error;
        }

        private void Page_Error(object sender, EventArgs e)
        {
            var ex = Server.GetLastError();

            // do something with exception
            Debug.WriteLine(ex);
        }
    }
}

Then if unhandled exception occurs in Page\UserControl logic, then it will call Error event, that will call this Page_Error method.

MSDN article about it - http://msdn.microsoft.com/en-us/library/ed577840(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

Upvotes: 1

Related Questions