Error when I am redirecting page - asp.net

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

Related

How to handle errors inside Catch block

In my application I am getting System.NullReferenceException for my REST call.
This Error is caused by code inside Catch block.
Is it a good idea to put another try catch block inside Catch block?
In the below code following line of code in Catch block is throwing error.
resultObject.ErrorResponse = _client.GetErrorResponse(Of List(Of ErrorResponseObject))(ex, "{""errors"":")
How do I fix this issue, so that user doesn't see any error.
Here is my code.
Public Shared Function POSTCall()
_client = New BaseClient()
Try
strJsonResponse = _client.ExecuteURI(serviceUrl, requestHeader, "POST", resultObject, False, False)
Catch ex As WebException
resultObject.ErrorResponse = _client.GetErrorResponse(Of List(Of ErrorResponseObject))(ex, "{""errors"":") 'This line causing error
If Not IsNothing(resultObject.ErrorResponse) Then
' do some work
End If
Catch Exp As Exception
'Supress the error. Let user goto next step.
Finally
_client = Nothing
End Try
Return resultObject
End Function
You have to catch the error Inside the catch block. This is especially appropriate since what the code is trying to do is to get more info about an error that has already occurrred. Of course, it might be a good idea to log any error occurring, even if the application can continue.
I prefer doing things that are not asynchronous inside the catch. In a case where I need to perform an asynchronous function say rolling back a database transaction, I'll just throw the error and have another asynchronous function handle it in it's catch block in a synchronous way

Difference between code cleanup in finally block and after catch block (C#)

What is the difference between adding cleanup code in finally block and cleanup code after the catch block ?
try
{
//some code
}
catch
{
}
finally
{
//cleanup
}
and
try
{
//some code
}
catch
{
}
//cleanup
If you throw a throwable from the try .. catch block that is not caught by this catch, the cleanup code inside the finally clause will execute and the code immediately after the catch block will not.
In your second case if the code rethrows an exception or return from the catch block then your cleanup code will not be called. In case of finally block it will be executed even if you have an exception or a return statement from the catch block.
The MSDN says:
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.

Application_Error takes precedence over Page_Error

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.
}
}

Server.Transfer does not work?

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.

exception (ab)use in web development

I find myself using exception in web development even for conditions that are not really errors, let alone exceptional ones - just logic decisions, validations...
in a web page, I often write code like so:
try
{
int id;
if(!int.TryParse(txtID.Text, out id))
throw new Exception("ID must be an integer");
if(IdAlreadyExists(id))
throw new Exception("ID already exists in database");
//and so on...
}
catch(Exception ex)
{
SetErrorLine(ex.Message);
}
I was wondering if this is really the correct way of using exceptions and enforcing Business Logic in web development.
P.S.: I am using asp.net, and obviously I could use ASP.NET validators for some of these and also seperate UI from logic, but I'm trying to make a point on the general idea.
You've just answered your own question, really.
Exceptions are for exceptional circumstances. Assuming the code you posted is from a page that takes "ID" as input from the user, then it's not exceptional for user input to be bad. Use the validation infrastructure for that, or do it manually, but don't use exceptions for that.
Also, don't get into the habit of displaying Exception.Message to users. It is meant for developers to see to know what went wrong and how to fix it.
I wouldn't consider the first example to be an acceptable use of an Exception. A user could easily screw up entering that information, and user input should be validated anyways.
An exception should be 'exceptional'. Something that you don't expect to happen, shouldn't happen or really don't want to happen. Anything that can be validated or handled before needing to throw an exception should just be treated like an error.
Different communities differ in their acceptable use of exceptions. The Python community is a little bit more liberal with their use of exceptions: http://wiki.sheep.art.pl/Ask%20for%20Forgiveness
I'm a fan of using them as long as it doesn't disrupt the logic of your application.
Just wanted to add that for asp.net adding a global exception handler HttpModule to catch unhandled exceptions is a very clean way to train yourself out of try/catch/finally abuse.
Throw exceptions when the assumptions your methods take on are broken, or if a method simply cannot complete.
In your example, your IdAlreadyExists method might query a database. That method will assume that there is a database to connect to, you have enough memory to do what you need, and so on. If an assumption is broken, throw an exception.
I, for one, like to let lower level code throw exceptions, and higher level code catch exceptions. That's not a hard and fast rule, just a general guideline I like to follow. It's typically not necessary to throw exceptions to the same level, but I could imagine that it would make sense at times.
still missing the way it SHOULD be done
Set an error mesage and return.
Log error and dont display it to user.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int id = 0;
if(!int.TryParse(txtID.Text, out id))
{
SetErrorLine("Thats not a valid number dude! Need to go to school again");
return;
}
if(IdAlreadyExists(id))
{
SetErrorLine("I already have this entry in store. Sorry. Call again!");
return;
}
...the rest of your code
}
catch(Exception ex)
{
_log.Error(ex);
SetErrorLine("Something unexpected happened dear user ... ");
}
}
Edit: your comment
try {
string error = "";
int id = 10;
if(BO.DoSomething(out error, id, otherParams))
{
SetErrorLine(error);
return;
}
}
catch(Exception ex)
{
//log
}
My guess:
try {
string meaningfullErrorMessage= "";
int id = 10;
if(!BO.DoSomething(out meaningfullErrorMessage, id, otherParams))
{
SetErrorLine(meaningfullErrorMessage);
return;
}
}
catch(Exception ex)
{
//log
}

Resources