Error Handling in ASP.NET MVC

Basically, there are two ways of customizing error handling in ASP.NET MVC.

One is to turn on customErrors in web.config and add HandleErrorAttribute in FilterConfig.cs or to a specific controller or method. This will display the Views/Shared/Error view.

A better approach is to add a Application_Error method in Global.asax where you can log the error. Here is an example with specific code for DbEntityValidationException (with credits to Slauma on Stackoverflow):

        protected void Application_Error(object sender, EventArgs e)
            var ex = Server.GetLastError();
            _log.Error("Error caught in Global.Application_Error", ex);
            var dbeve = ex as System.Data.Entity.Validation.DbEntityValidationException;
            if (dbeve != null)
                StringBuilder sb = new StringBuilder();
                foreach (var eve in dbeve.EntityValidationErrors)
                    sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().FullName, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                        sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",

If you just want to see the details of a DbEntityValidationException during debugging, you can add a watch with the name “((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors”.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s