how to catch all error in C# MVC (error handling)

I have a website in C# MVC and I want to add a feature to it, i.e, to save all the errors in database using one function only, I can place try/catch block in every method of the web applications but it would be lengthy process, so is it possible to place a method/code in one place from where I can save each and every error in database??
I have no idea



Asked by:- jaiprakash
: 3831 At:- 5/31/2017 3:51:33 PM
C# Error handling

1 Answers
profileImage Answered by:- vikas_jk

Thank you for asking a question here.

You can place this method in Global.asax which will be executed, whenever error occurs in application

protected void Application_Error(object sender, EventArgs e)
            Exception exception = Server.GetLastError();

            HttpException httpException = exception as HttpException;

            if (httpException != null)
                string action;

                switch (httpException.GetHttpCode())
                    case 404:
                        // page not found
                        action = "HttpError404";
                    case 500:
                        // server error
                        action = "HttpError500";
                        action = "General";

                // clear error on server
                 //Save error details in database
                using (var context = new DatabseCOnnection())
                    var Error = new ErrorDetail();
                    Error.ErrorMessage = exception.Message;
//Redirect to ErrorController method based on error type
               Response.Redirect(String.Format("~/Error/{0}", action));

that's it

You might also like to add Custom Error pages to show a user a friendly error message in MVC, so here is the article for it :

At:- 6/1/2017 6:29:57 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use