Wednesday, 20 January 2016

MVC - Error Handling - How to create default custom error page

Watch this example on YouTube:


here are the steps from the video above
1. Rename Shared\Error.cshtml to Shared\_Error.cshtml
2. add the following method to global.asax.cs file
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exc = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/ErrorPage/ErrorMessage");
        }
3. create new controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication3.Controllers
{
    public class ErrorPageController : Controller
    {
        //
        // GET: /ErrorPage/

        public ActionResult ErrorMessage()
        {
            return View();
        }

    }
}
4. create new view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication3.Controllers
{
    public class ErrorPageController : Controller
    {
        //
        // GET: /ErrorPage/

        public ActionResult ErrorMessage()
        {
            return View();
        }

    }
}
5. add the following code to home controller to cause error
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            int x = 2;
            if (x == 2)
            {
                throw new Exception("test");
            }
           
            return View();
        }

No comments:

Post a Comment