create custom error page for exception handling in asp.net mvc
Microsoft Net Framework


To create a custom error page in ASP.NET MVC that is displayed when an exception is thrown and caught by your code, you can use exception handling in combination with the HandleErrorAttribute attribute. Here are the steps to follow:

Create a new view file for your custom error page. For example, you might create a file called Error.cshtml in the Views/Shared folder.

In your Web.config file, add the following lines to the <system.web> section:


Exact Code


<customErrors mode="Off"/>
This will disable the default error handling behavior in ASP.NET MVC.

Add the [HandleError] attribute to your controller class or to individual controller actions that should handle exceptions. For example:


Exact Code
[HandleError]
public class HomeController : Controller
{
    // ...
}
In your Global.asax.cs file, override the Application_Error method and add code to log the error and redirect to the custom error page. For example:

Exact Code
protected void Application_Error()
{
    Exception exception = Server.GetLastError();
    // Log the exception here, if desired
    Response.Clear();
    Server.ClearError();
    Response.RedirectToRoute("Default", new { controller = "Error", action = "Index" });
}

This code clears the response, clears the error, and then redirects to the Error controller's Index action.

In your custom error page, you can access the exception details using the Model property. For example, you might display the exception message like this:


Exact Code

<h2>An error occurred:</h2>
<p>@Model.Exception.Message</p>
With these steps, any exceptions that occur in your application will be caught by the HandleError attribute and redirected to the custom error page. You can customize this page to display helpful information about the error, or to include links to additional resources for troubleshooting.

Share This with your friend by choosing any social account


Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM