Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle exceptions in entity framework 4

I need a way to distinguish between SQL exceptions using entity framework LINQ, for example how to distinguish foreing key constraint violation, or unique constraint violation when all i get from the DbUpdateException is a ton of nested inner exceptions and useless long error messages? Are there any lower level exceptions where i can do something like "Catch FKException"; catch "uniqueException" or something like that.

like image 428
Cristiano Coelho Avatar asked Sep 27 '13 03:09

Cristiano Coelho


People also ask

How do you handle specific exceptions?

In general, it's good programming practice to catch a specific type of exception rather than use a basic catch statement. When an exception occurs, it is passed up the stack and each catch block is given the opportunity to handle it. The order of catch statements is important.

How do you handle exceptions in .NET core?

To handle exceptions and display user friendly messages, we need to install Microsoft. AspNetCore. Diagnostics NuGet package and add middleware in the Configure() method. If you are using Visual Studio templates to create ASP.NET Core application then this package might be already installed.

How do you handle exceptions in API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

How do I fix exceptions in C#?

Use a try block around the statements that might throw exceptions. Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.


1 Answers

            try
            {
                //code
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                string rs = "";
                foreach (var eve in e.EntityValidationErrors)
                {
                    rs = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    Console.WriteLine(rs);

                    foreach (var ve in eve.ValidationErrors)
                    {
                        rs += "<br />" + string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw new Exception(rs);
            }
like image 171
Mr.LamYahoo Avatar answered Oct 24 '22 09:10

Mr.LamYahoo