Created
July 11, 2013 21:50
-
-
Save 4E71/5979569 to your computer and use it in GitHub Desktop.
Demonstrate unwrapping exception to provide useful troubleshooting message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void SaveChanges() | |
{ | |
try | |
{ | |
_context.ChangeTracker.DetectChanges(); | |
_context.SaveChanges(); | |
} | |
catch (DbEntityValidationException ex) | |
{ | |
// Retrieve the error messages as a list of strings. | |
var errorMessages = ex.EntityValidationErrors | |
.SelectMany(x => x.ValidationErrors) | |
.Select(x => x.ErrorMessage); | |
// Join the list to a single string. | |
var fullErrorMessage = string.Join("; ", errorMessages); | |
// Combine the original exception message with the new one. | |
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); | |
// Throw a new DbEntityValidationException with the improved exception message. | |
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment