Search code examples
c#http-redirecterror-handlingasp.net-mvc-5sqlexception

ASP.NET MVC SqlException does not redirect to error page


I expect that if an error occurs (for example, I've typed wrong address of site's page), user will be redirected to a relevant error page (in this case - 404). But for error type 500 (Internal server error), I see redirection in VS Log, but user stays on the same page, which caused the error.

Here is how my webpage works:

  1. When user opens the webpage, controller's ActionResult method is executed and returns View();

  2. View renders html code and, then launches jQuery ajax which executes another controller method with a JsonResult

  3. In this controller method, a SQL query is prepared and executed through static class method which uses SqlClient

  4. In the static class method, I get a SqlException (for example, I try to execute non-existing procedure):

    An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

    Additional information: Cannot find stored produre "dbo.NonExistingProcedureName".

I expected that in this case, user will be redirected to 500 error page, and I see the redirection in VS log:

Event Type Event Time Duration Thread Detail Description

ASP.NET (Activated)
Redirect to "/error/serverError?aspxerrorpath=/dash/jObject" 11.16s [24128]
Worker Thread
...

ASP.NET GET "/error/serverError" 11.16s [24128] Worker Thread

... but redirect is not actually completed, and user still looks at the page which caused the error.

So, why does the redirect to the error page not work as expected?


Solution

  • If I've read this correctly, your 500 error is occurring in the ajax request. If that is the case then the error page is being returned, but not rendered. If you look in your dev tools in a browser at the response of the failed ajax request you will see the error page. The whole advantage of ajax is that you don't have to post an entire form back, allowing you to only render sections that you want to update. Therefore if you want to redirect to another page, you'll need to handle this in your javascript.

    It's best to catch the error on your ajax error or statusCode callback and then redirect to the relevant error page via javascript. Something like...

    $.ajax({
    statusCode: {
        500: function() {
          alert("fudged up");
        }
      }
    });