ASP.NET 2.0 - Errors while re-directing user to an error page after the exception is thrown from COM Port

Abstract

=======

There is an ASP.NET 2.0 application inside of which i connect to serial COM port by using the classes present in System.IO.Port namespace (https://msdn2.microsoft.com/en-us/system.io.ports.serialport.aspx). I am able to connect to COM port, fetch the data and trap the exceptions when the device is disconnected, successfully. When some device is disconnected from the COM port I want the user to redirect to an error page within the exception handler code. In order to do this, using Response.Redirect/ Server.Transfer will give me the error message below: -

 

"Response is not available in this context"

 

Cause

=====

This is an expected behavior because HTTP Context is not available in at that point of time. As a result, we cannot use any of the classes present inside http context i.e. response, request, session etc. It is not available because exception handler event is fired not due to page post back, but because of external change event. As far as page life cycle goes http context is built when page is requested and gets destroyed after the page is served/rendered.

 

To get more understanding on the page life cycle, please visit the following link: -

https://msdn2.microsoft.com/en-us/library/ms178472.aspx

 

Resolution/ Workaround

==================

I created a static boolean variable at the page level and initialized it to false. When the exception will occur, I will simply set the variable to true (in the exception handler code). Also, I will keep refreshing the page lets say, after every 5 seconds and keep checking for its value in the page load. If value comes out to be true, we will simply redirect user to the error page.