narutouzumaki 99
narutouzumaki 99

Reputation: 107

Redirecting after click on button throws error ASP.NET

I used regular button to throw span into button. I also made onServerClick function (to handle the event).

<button id="btnCancel" runat="server" class="btn btn-default pull-right" onserverclick="btnCancel_Click"><span class="glyphicon glyphicon-remove text-magenta"></span>Cancel</button> 

This should be simple cancel button that should exit the form and noting else. But for some reason C# function throws exception on redirect.

Here is the function:

            try
        {
            Response.Redirect("StartPage.aspx");
        }
        catch (Exception ex)
        {
            NLog.LogManager.GetCurrentClassLogger().Warn("Error happened", ex);
            Response.Redirect("Error.aspx", false);
        }

Also if I just dont put try and catch block everything works fine.

Upvotes: 0

Views: 163

Answers (1)

Markus
Markus

Reputation: 22456

Response.Redirect throws a ThreadAbortException that is caught by your exception handler. Either

  • remove the exception handler (if the real-life code is as simple as your sample, there should be no need for an exception handler) or
  • move the Response.Redirect out of the exception handler or
  • create a dedicated handler for the ThreadAbortException like this:

try
{
    Response.Redirect("StartPage.aspx");
}
catch (ThreadAbortException)
{
  // Exception is expected, do nothing
}
catch (Exception ex)
{
    NLog.LogManager.GetCurrentClassLogger().Warn("Error happened", ex);
    Response.Redirect("Error.aspx", false);
}

Upvotes: 1

Related Questions