Response.Redirect exception inside try / catch block

Let's say I have a try / catch block that encapsulates a large block of code, and then somewhere in it I need to call Response.Redirect as such:

protected void ButtonGo_Click(object sender, EventArgs e) { try { using(lockingMethod) { //Code... //Somewhere nested in the logic Response.Redirect(strMyNewURL); //More code... } } catch(Exception ex) { LogExceptionAsError(ex); } } 

What happens in this case is that Response.Redirect throws an exception, something about the termination of the stream, which, in my opinion, is a "normal event stream" for this method, but it is logged in my LogExceptionAsError as an error, therefore I was curious if there is a way to make a Response.Redirect exception thrown?

+6
source share
2 answers

Try an alternative version of Response.Redirect

 Response.Redirect(strMyNewURL, false); 

It will complete the loading of the current page.

+4
source

Response.Redirect completes the current execution and thus redirects immediately by throwing this exception so that it is not processed. This is intentional and by design. You should not catch yourself in most cases - this defeats the goal. If you want to complete code execution before redirecting, you can use overloading:

 Response.Redirect(somewhere, false); 

Which will NOT throw an exception. This may be ineffective if you do not need to do anything else before redirecting.

Please note that this is usually a logical thread controlled by an anti-pattern using exceptions and catching exceptions ... However, it makes sense to do this for this particular method, since redirection usually does not require any additional logic to execute - it just answers 302 and the new address for the transition.

+2
source

Source: https://habr.com/ru/post/948515/


All Articles