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.
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With