0

I'd like to use the Error event of an ASPX page to catch any unhandled exceptions that occur in that page and set the text of a label control to display the error to the user (I realize this is likely not a recommended best practice, this is a quick and dirty).

So, in the error event, I would have something like:

Me.lblError.Text = Server.GetLastError.Message

However, when I run this and the error occurs, I can see this line is executing by setting a breakpoint, but the screen always ends up blank. I have tried with and without a Server.ClearError after setting the text, but the result is the same.

Shouldn't this be possible??

Update

See correct answer below, as well as this article:
http://msdn.microsoft.com/en-us/library/ed577840.aspx

2 Answers 2

1

You cannot impact the Text property of the Label control inside this event. This has to do with the page execution model of ASP.NET.

You can, however, still write information to the screen. You can do so using Response.Write. The following shows an example:

protected void Page_Error(object sender, EventArgs e)
{     
    Exception exc = Server.GetLastError();        
    Response.Write(exc.Message);
    Server.ClearError();
}

You should consider, however, a global error handler in the .asax.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems to be the correct answer, writing to your controls seems to be absolutely not possible. I have not been able to find this stated explicitly anywhere, but it seems to be the case. So apparently, you have to Try...Catch everything, everywhere in ASPX pages. If anyone happens to know of a clever workaround, please post it.
It is explicitly stated as, "A page-level handler returns you to the page, but there is no longer anything on the page because instances of controls are not created. To provide the user any information, you must specifically write it to the page." You can find this information on MSDN at: msdn.microsoft.com/en-us/library/ed577840.aspx. Hope this helps.
Excellent article, something that actually explains whats going on.
1

Typically I would see this at the Global.asax level, and redirect to an error page. Rather than handling on the page itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.