Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes 'Thread was being aborted' exception to happen at random and show the HTTP header and partial HTML to the browser?

What is happening is occasionally at random instead of the HTML being returned to the browser as you would expect, it looks a little something like this:

Thread was being aborted.HTTP/1.1 200 OK

(the rest of the header)

... (like 1/10th of the HTML)

That's it, they are literally getting a bunch of text in the browser window.

It doesn't happen all the time, just randomly. Computers... in my experience always have a reason for everything, ALWAYS. So what's the heck is going on here?

I have searched the entire solution and found quite a few calls to Response.Redirect() which seems like it could be the culprit based on other questions I have read...

this is all well and good but it does not tell me why it would be happening at random

...or why it would be giving this strange result back to the browser rather than the normal custom error page we have setup. If this is indeed what is causing it, which I have not yet determined. If it is, I don't think I can simply add the 'false' parameter because I don't know what that would do if it kept executing the current code.

like image 786
MetaGuru Avatar asked Dec 28 '22 21:12

MetaGuru


1 Answers

When you call Response.End (which is called by other methods like Response.Redirect and Server.Transfer) the executing thread is aborted and a ThreadAbortException is thrown (aborting threads are not exceptional in ASP.NET). You can catch this exception but it will always be rethrown in the catch handler. This sets it apart from other exception types but it makes sense because you should not be able to stop a thread from aborting and in the process clean up the stack by executing finally blocks.

Perhaps you have some exception handling logic where Response.End is called inside a try block and the unexpected output is produced in the catch block?

Something like this (probably more convoluted and hard to track in a "mature" code base):

void HandleRequest() {
  try {
    Response.Redirect(...);
  }
  catch (Exception ex) {
    Response.Write(...);
  }
}

If the Response.Redirect ends with Response.End a ThreadAbortException is thrown and the Response.Write will execute adding text to the response.

like image 110
Martin Liversage Avatar answered Jan 02 '23 23:01

Martin Liversage