开发者

Redirect to error page

I want to use Response.Redirect to redirect the browser when an exception occurs.

I also want to pass the exception message to my error page.

For example:

string URL = "Page2.aspx?Exception=" + ex.ToString()
Response.Redirect(URL)

Can it be done? Is th开发者_StackOverflow社区is the right syntax?


Instead of Response.Redirect, which sends a response to the client asking it to request a different page, you should call Server.Transfer, which runs a different page immediately and sends that page directly to the client.

You can then put the exception in HttpContext.Items and read it from HttpContext.Items in your error page.

For example:

catch (Exception ex) {
    HttpContext.Current.Items.Add("Exception", ex);
    Server.Transfer("Error.aspx");
}

In Error.aspx, you can then get the exception like this:

<% 
    Exception error;
    if (!HttpContext.Current.Items.Contains("Exception"))
       Response.Redirect("/");  //There was no error; the user typed Error.aspx into the browser
    error = (Exception)HttpContext.Current.Items["Exception"];
%>


Yes that would work (with some semicolons added of course and you probably just want to send the exception message):

String URL = "Page2.aspx?Exception=" + ex.Message;
Response.Redirect(URL);


As Andrew said, it should work.

However, if you're looking for Error Management, you're better off using Server.GetLastError() so you get the full Exception object including stack trace.

Here's an MSDN article that deals with Application Errors in general and uses Server.GetLastError().


Typically I would have panels in my page and toggle visibility in the catch block to display a friendly message to the user. I would also include an emailed report to myself detailing the error message.

try
{

}
catch (Exception ex)
{
    formPanel.Visible = false;
    errorPanel.Visible = true;

    // Log error
    LogError(ex);
}

As for reporting/forwarding the error to another page:

string errorURL = "ErrorPage.aspx?message=" + ex.Message;
Response.Redirect(errorURL, true);

And don't forget ELMAH! http://bit.ly/HsnFh


We would always advise against redirecting to a .aspx page on an error condition.

In the past we've seen scenarios where a fundamental issue with the application has caused an error to occur, which has in turn redirected to an error.aspx page, which it's self has errored resulted in an endless redirection loop.

We strongly advise people to use a .htm page or something which is not handled by the ASP.NET framework for error pages.

There is built in support within ASP.NET using the customErrors section of the Web.config to automatically handle error redirection for you.

customError tag

You can look into global exception handling too, this can be managed via the Application_OnError event which you can find within the global.asax

Thanks,

Phil

http://exceptioneer.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜