Blog

Filter posts by Category Or Tag of the Blog section!

Handling custom error in asp.net mvc

Wednesday, 13 January 2016

In asp.net MVC there is a custom error in web.config like below:

<customErrors mode="On">

<error statusCode="404" redirect="~/404.html"/>

</customErrors>

 

Sometimes you want to redirect the user to your own custom error controller and log the error message. You can handle it! Firstly create your own Error controller:

 

public class ErrorController : Controller

    {

        public ActionResult HttpError404()

        {

            return View("HttpError404");

        }



        public ActionResult HttpError500()

        {

            return View("HttpError500");

        }



        public ActionResult General()

        {

            return View("General");

        }

    }

 

Secondly, you need to handle this controller in a higher level in your application, refer to global.asax and create the Application_Error method with the following definition:

protected void Application_Error(object sender, EventArgs e)

        {

            Exception exception = Server.GetLastError();        

            Response.Clear();

            HttpException httpException = exception as HttpException;

            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");



            if (httpException != null)

            {

                switch (httpException.GetHttpCode())

                {

                    case 404:

                        routeData.Values.Add("action", "HttpError404");

                        break;

                    case 500:

                        routeData.Values.Add("action", "HttpError500");

                        break;

                    default:

                        routeData.Values.Add("action", "General");

                        break;

                }

            }



            routeData.Values.Add("error", exception);

            Server.ClearError();

            Response.TrySkipIisCustomErrors = true;

            IController errorController = new ErrorController();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }

 

Done! Now you can create your own Views of ErrorController and have your handled ErrorController.

Category: Software

Tags: Asp.Net

comments powered by Disqus