简体   繁体   中英

try catch on ExecutionTimeout not working

This one has been the source of much torment for me! I am using the global ExecutionTimeout of 110 seconds for my application. One particular page generates a great number of unhandled exceptions as it contains a FileUpload control.

Now here is the problem...I know how to limit the file size and the execution timeout in the web.config using the following declarations.

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

The problem I have is right here:

    'Check file size
    Dim fileSize As Integer
    Try
        fileSize = FileUpload1.FileBytes.Length
    Catch ex As Exception
        'Display message to user...
        Exit Sub
    End Try

The very process of checking the file length quite frequently throws an exception, and that exception isn't caught gracefully in the above try, catch , it seems to defer to the application level exception handling in the global.asax.

I'm pretty sure I can't check the file size on the client-side, I don't want to keep bumping up the maxRequestLength and executionTimeout , all I'm looking to do is catch those timeouts on the page and display a message. Is this possible?

EDIT ---

To better illustrate the problem here, try running the following code (assumes your default executionTimeout is 110 seconds).

    Try
        system.threading.thread.sleep(120000)
    Catch ex As Exception
        response.write("Error caught!!")
        Exit Sub
    End Try

Make sure debug is switched off. The catch block won't work and you'll end up with an unhandled System.Web.HttpException: Request timed out error, this I have yet to figure out?

Turns out the code on the page isn't directly throwing the exception here, hence why it's not getting caught in the try, catch . The application monitors and intervenes when a script takes too long to execute, so when the exception is raised at the application level we need to defer to the global.asax.

The solution involves trapping the error in the Global.asax Application_Error block then response.redirecting back to the originating page with the error type appended to the query string.

 Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim exc As Exception = Server.GetLastError
        Dim context As HttpContext = DirectCast(sender, HttpApplication).Context

        Dim uri As String = context.Request.Url.PathAndQuery

        If uri.Contains("users/account.aspx") Then
            Response.Redirect(context.Request.Url.PathAndQuery & "&err=" & exc.GetType().ToString)
        End If
End Sub

You can then check in the page load for any err querystring value then display the error accordingly on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM