I have both Page_Error method in page that raises error, and Application_Error in global.asax. When Page throws exception, executed routine is Application_Error. But for that one particular page I would like to have different handling in Page_Error. Is there any way to achieve it?
Thanks,
Pawel
P.S. Perhaps it is because exception being thrown is caused by too large file being uploaded (I tested file upload page how it handles files bigger then web.config setting) and Page_Error is not yet wired?
From the same the function of Page_Error you can check for the page and if is the one you look you have diferent behavior.
if( HttpContext.Current.Request.Path.EndsWith("YourFileName.axd", StringComparison.InvariantCultureIgnoreCase))
{
// the diferent way
}
else
{
}
The next way is from inside the page with the diferent behavior.
public override void ProcessRequest(HttpContext context)
{
try
{
base.ProcessRequest(context);
}
catch (Exception x)
{
// here is the different, since you catch here is not move to the Page_Error
// except is a code error... in any case you can do an extra error clear.
}
}
Related
Does HealthMonitoring have a built-in event that catches 404 errors? I have tried setting up all events (by using webBaseEvent) and I've searched for two days, but I cannot find or trigger an event for a file not found.
I could create my own, but was hoping there was a built in event.
No, it doesn't. You'd have to create a custom event (from webrequesterrorevent) to have HM track it for you.
How to:
Something like this (from memory) in Application_Error in global.asax -
public void Application_Error()
{
var exception = Server.GetLastError() as HttpException;
if (exception != null && exception.GetHttpCode() == 404)
{
//custom error
new Http404Event(this, exception).Raise();
}
}
I understand (now) that Response.Redirect() and Response.End() throw a ThreadAbortException as an expensive way of killing the current processing thread to emulate the behaviour of ASP Classic's Response.End() and Response.Redirect methods.
However.
It seems intermittently in our application that the exception bubbles too high. For example, we have a page that is called from client side javascript to return a small string to display in a page.
protected void Page_Load(object sender, EventArgs e)
{
// Work out some stuff.
Response.Write(stuff);
Response.End();
}
This generally works, but sometimes, we get the exception bubbling up to the UI layer and get part of the exception text displayed in the page.
Similarly, else where we have:
// check the login is still valid:
if(!loggedin) {
Response.Redirect("login.aspx");
}
In some cases, the user is redirected to login.aspx, in others, the user gets an ASP.NET error page and stack dump (because of how our dev servers are configured).
i.e. in some cases, response.redirect throws an exception all the way up INSTEAD of doing a redirect. Why? How do we stop this?
Have you tried overloading the default Redirect method and not ending the response?
if(!loggedin) {
Response.Redirect("login.aspx", false);
}
You can use the following best-practice code instead, as explained by this answer to prevent the exception from happening in the first place:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
Since I was looking for an answer to this question too, I am posting what seams to me a complete solution, rounding up the two above answers:
public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
Page page = control.Page;
if (!ignoreIfInvisible || page.Visible)
{
// Sets the page for redirect, but does not abort.
page.Response.Redirect(url, false);
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline
// chain of execution and directly execute the EndRequest event.
HttpContext.Current.ApplicationInstance.CompleteRequest();
// By setting this to false, we flag that a redirect is set,
// and to not render the page contents.
page.Visible = false;
}
}
Source:
http://www.codeproject.com/Tips/561490/ASP-NET-Response-Redirect-without-ThreadAbortExcep
Our ASP.NET 2 web application handles exceptions very elegantly. We catch exceptions in Global ASAX in Application_Error. From there we log the exception and we show a friendly message to the user.
However, this morning we deployed the latest version of our site. It ran ok for half an hour, but then the App Pool crashed. The site did not come back up until we restored the previous release.
How can I make the app pool crash and skip the normal exception handler? I'm trying to replicate this problem, but with no luck so far.
Update: we found the solution. One of our pages was screenscraping another page. But the URL was configured incorrectly and the page ended up screenscraping itself infinitely, thus causing a stack overflow exception.
The most common error that I have see and "pool crash" is the loop call.
public string sMyText
{
get {return sMyText;}
set {sMyText = value;}
}
Just call the sMyText...
In order to do this, all you need to do is throw any exception (without handling it of course) from outside the context of a request.
For instance, some exception raised on another thread should do it:
protected void Page_Load(object sender, EventArgs e)
{
// Create a thread to throw an exception
var thread = new Thread(() => { throw new ArgumentException(); });
// Start the thread to throw the exception
thread.Start();
// Wait a short while to give the thread time to start and throw
Thread.Sleep(50);
}
More information can be found here in the MS Knowledge Base
Aristos' answer is good. I've also seen it done with a stupid override in the Page life cycle too when someone change the overriden method from OnInit to OnLoad without changing the base call so it recursed round in cirlces through the life cycle: i.e.
protected override void OnLoad(EventArgs e)
{
//some other most likely rubbish code
base.OnInit(e);
}
You could try throwing a ThreadAbortException.
I want to redirect to another page using Server.Transfer and I have this simple code:
if (Page.IsPostBack)
{
try
{
Server.Transfer("AnotherPage.aspx");
}
catch (Exception)
{
throw ;
}
}
But I'm getting an error: "Error executing child request for AnotherPage.aspx.". Could not find the solution on the net.
Just to mention, Response.Redirect works flawlessly.
The error is likely caused by something in AnotherPage.aspx. You may want to insert a try... catch handler in AnotherPage.aspx's Load event.
I am getting an error:
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
when I am redirecting my page from one to another.
I am using this code:
try
{
Session["objtwitter"] = obj_UserDetSumit;
Response.Redirect("TwitterLogin.aspx");
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
}
And I got a solution and I tried also this Response.Redirect("home.aspx",false);
It's not throwing an error but it's also not redirecting page.
Try - catch creates a thread around code within it in order to catch exceptions. When you Redirect you are effectively terminating execution of the thread thus causing an error since execution ended unnaturely (though this is by design). You should not Redirect from within try-catch and if you do you should use Response.Redirect( "some url", false ); and also specifically catch ThreadAbortException.
Reference here: http://msdn.microsoft.com/en-us/library/t9dwyts4.aspx
Response.Redirect calls the Response.End, which throws a ThreadAbortException, so you'd want to change your code to:
try
{
Response.Redirect("home.aspx");
}
catch(System.Threading.ThreadAbortException)
{
// do nothing
}
catch(Exception ex)
{
// do whatever
}
First, make sure that you are working with a debug build and not a release build of your project. And second, make sure that you are debugging in mixed mode (both managed and native) so that you can see all of the current call stack.
I'd try moving your Response.Redirect outside of the try catch block like this:
try
{
Session["objtwitter"] = obj_UserDetSumit;
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
return;
}
Response.Redirect("TwitterLogin.aspx");
Most people having this issue here resolved it with calling Response.Redirect("TwitterLogin.aspx", false); which doesn't explicitly kill the thread immediately. I'm not sure why this didn't work for you.
I think the issue is having your Response.Redirect inside of a try catch block. Calling Response.Redirect(url); calls Response.End();, which will throw a ThreadAbortException.
Make sure you're not trying to do any more processing after you do your redirect.
Using Reflector, you can see that Response.Redirect(url); calls Response.Redirect(url, true);
Passing true then calls Response.End(); which looks like this:
public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
....
}
Even though you don't have a finally in your code snippet, it may be trying to execute the "empty" finally, but can't because the thread is being aborted. Just a thought.
If you replace your code these line you won't get an exception in the first place
try
{
Response.Redirect("home.aspx", False);
//Directs the thread to finish, bypassing additional processing
Context.ApplicationInstance.CompleteRequest();
}
catch(Exception ex)
{
// exception logging
}
Hope it helps