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
2
: 1557 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();
            Response.Clear();

            HttpException httpException = exception as HttpException;

            if (httpException != null)
            {
                string action;

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

                // clear error on server
                Server.ClearError();
                 //Save error details in database
                using (var context = new DatabseCOnnection())
                {
                    var Error = new ErrorDetail();
                   
                    Error.ErrorMessage = exception.Message;
                 
                    context.ErrorDetails.Add(Error);
                    context.SaveChanges();
                }
//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 : https://qawithexperts.com/article/asp-net/custom-error-pages-in-aspnet-mvc/242

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






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

Full Name *

Email *




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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly