Search code examples
c#asp.netweb-config

how to redirect 500 error to default error page for asp.net application


i need to redirect to default error page for 500 error or for wrong url. i tried below changes in config but it dint work

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/GenericError.aspx">
        <error statusCode="404" redirect="~/GenericError.aspx"/>
        <error statusCode="500" redirect="~/GenericError.aspx"/>
        <error statusCode="302" redirect="~/GenericError.aspx"/>
</customErrors>

Here is Error snapshot : when i try to do small change in url

enter image description here


Solution

  • Here is what I use. This also includes grabbing the exception and setting it as an application variable in case you need to relay that info, and prevents infinite loops if there is an error on the error page.

    In the Global.asax file:

    public void Application_Error(object sender, EventArgs e)
    {
        // Fires when an error occurs
        // Code that runs when an unhandled error occurs
        Exception ex = Server.GetLastError();
        // store the error for later
        Application["TheException"] = ex;
        Server.ClearError();
    
        if (Request.Url.PathAndQuery.Contains("GenericError.aspx") == false)
            Response.Redirect("~/GenericError.aspx");
    }