Program Flow via Custom Exception - c#

I have a process that is parsing an XML file.
This is occuring in the PAckage Class.
The Package class has a Delegate that sets the object to an invalid state and captures the detailed info on error that occured the Package Class
For simplicity I am showing the filitem being passed to the package..
i.e `
foreach( var package in Packages)
{
try
{
package.ProcessXml(fileitem.nextfile);
}
catch (CustomeErrorException ex)
{
Logger.LogError(ex)
}
}
Inside The Package my validations look something like this
var Album = xml.Descendants()
.Select(albumShards => new Album {
Label = (string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault() == "" ?
FailPackage("Error on label Load",Componets.Package,SubComp.BuildAlbum ) : (string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault()
On this validation I check to see if "" is returned for label... if so Call Failpackage with error info and create exception
protected override void FailPackage(string msg, LogItem logItem)
{
Valid = ProcessState.Bad;
Logger.LogError(msg,logItem);
throw CustomErrorException(msg, Logitem);
}
that is captured via the containing try catch block
My concern is that I am using Exceptions for Program flow ... how else should I look at approaching this problem or is this a valid Pattern.

ProcessXml fails to do what its name implies in certain cases; these are error cases. Exceptions are for error handling, despite what the name implies.
One of the biggest misconceptions about exceptions is that they are
for “exceptional conditions.” The reality is that they are for
communicating error conditions.
Krzysztof Cwalina, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
In other words, you're in the right. :)
Read the chapter on exceptions in the above book for some excellent guidelines.

You can put the error along with the ProcessState:
foreach( var package in Packages)
{
package.ProcessXml(fileitem.nextfile);
if(!package.Valid)
Logger.LogError(package.Error)
}
var albumShards = xml.Descendants().FirstOrDefault();
if((string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault() == "")
return FailPackage("Error on label Load",Componets.Package,SubComp.BuildAlbum );
album = (string)albumShards.Descendants(TempAlbum.LabelLoc);
protected override void FailPackage(string msg, LogItem logItem)
{
Valid = ProcessState.Bad;
Logger.LogError(msg,logItem);
Error = msg;
}

Related

ELMAH exceptions generating generic "The service is unavailable" message

I'm trying to create an availability page which checks all the services that a site uses, wrapping each check in a try/catch and then displaying any failures to the users. One of those services is ELMAH, so I am calling that to double check that we can log errors there successfully.
Controller:
var a = new AvailabilityModel();
try {
a.ElmahConnectionString = ConfigurationManager.ConnectionStrings["elmah-sqlserver"].ConnectionString;
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Elmah availability test"));
a.ElmahSuccess = true;
} catch (Exception ex) {
a.ElmahSuccess = false;
a.ElmahException = ex;
Response.StatusCode = 503;
}
return View(a);
When ELMAH succeeds, all is well. When it throws any kind of error (DB permissions, etc.), I get an error which is not captured by the try/catch OR by any of the normal error-capturing pieces: ASP.NET MVC HandleError, customErrors redirects, or even httpErrors in system.webServer. The display is not the normal IIS generic message, instead I see a single line saying "The service is unavailable."
Response:
LTSB-W34511 C:\s\d\build % curl -i http://server/test/availability
HTTP/1.1 503 Service Unavailable
Cache-Control: public, max-age=14400, s-maxage=0
Content-Type: text/html
Server: Microsoft-IIS/7.5 X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 06 Aug 2014 15:46:55 GMT
Content-Length: 27
The service is unavailable.
And that's it. At least I know my availability is not working, but I want to at least display to the user that it's ELMAH causing the problem, and show the connection string it's trying to use. So, I need to capture this exception somehow.
I've tried tweaking my web.config a number of different ways, but I suspect there's something about the way ELMAH inserts itself into the module pipeline which stops me from handling the issue.
Edit:
To clarify, this is a simplified example. I am not planning to expose this information to end users. This availability page will only be available to internal users who are troubleshooting future issues.
ELMAH is only one of the services/databases used by the application in question, and I want to give administrators a quick dashboard-like view of what is up and down. I can't do that if ELMAH errors lead to this insta-503.
Ok, basically this is not possible without any code. The Raise method in Elmah will not let you see any error except if you trace it:
// ErrorLogModule.LogException
try
{
Error error = new Error(e, context);
ErrorLog errorLog = this.GetErrorLog(context);
error.ApplicationName = errorLog.ApplicationName;
string id = errorLog.Log(error);
errorLogEntry = new ErrorLogEntry(errorLog, id, error);
}
catch (Exception value)
{
Trace.WriteLine(value);
}
However when the event is successfully logged the ErrorLogModule will call the logged event in order to let potential listeners know that the logging was a success. So let's quickly write a custom class that will override some methods from the ErrorLogModule and will allow us to notice that the event was not logged:
public class CustomErrorLogModule: Elmah.ErrorLogModule
{
public Boolean SomethingWasLogged { get; set; }
protected override void OnLogged(Elmah.ErrorLoggedEventArgs args)
{
SomethingWasLogged = true;
base.OnLogged(args);
}
protected override void LogException(Exception e, HttpContext context)
{
SomethingWasLogged = false;
base.LogException(e, context);
if (!SomethingWasLogged)
{
throw new InvalidOperationException("An error was not logged");
}
}
}
Swap the ErrorLogModule with the CustomErrorLogModule in your configuration file and Elmah will complain when something wrong is happening; calling Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("test")); in a test page lets the InvalidOperationException("An error was not logged") be thrown out of the call.
If you want to get back the exact exception that occured when trying to log the exception, you can use the fact that the ErrorLogModule traces the exception when it occurs. Create a listener class:
public class ExceptionInterceptor : DefaultTraceListener
{
public Exception TracedException { get; set; }
public override void WriteLine(object o)
{
var exception = o as Exception;
if (exception != null)
{
TracedException = exception;
}
}
}
Then your LogException method becomes
protected override void LogException(Exception e, HttpContext context)
{
var exceptionListener = new ExceptionInterceptor();
Trace.Listeners.Add(exceptionListener);
try
{
SomethingWasLogged = false;
base.LogException(e, context);
if (!SomethingWasLogged)
{
throw exceptionListener.TracedException;
}
}
finally
{
Trace.Listeners.Remove(exceptionListener);
}
}
EDIT: or even if you want to be as terse as possible
public class ExceptionInterceptor : DefaultTraceListener
{
public override void WriteLine(object o)
{
var exception = o as Exception;
if (exception != null)
{
throw exception;
}
}
}
// snip... LogException in your CustomErrorLogModule
protected override void LogException(Exception e, HttpContext context)
{
var exceptionListener = new ExceptionInterceptor();
Trace.Listeners.Add(exceptionListener);
try
{
base.LogException(e, context);
}
finally
{
Trace.Listeners.Remove(exceptionListener);
}
}
One final word: There is a smell in this way of checking for service availability, and you are going to pepper your error database with test exceptions which may not be the desired behavior. I understand that you aim to check the whole logging chain but perhaps there could be some other way to do it; I don't really know your context so I won't comment any further but don't hesitate to think on it.
Anyway, these changes should let you receive the exception you will need.
important edit: very important point: you may want to add a trigger to your CustomErrorLogModule so it doesn't throw when you are not testing. The resilience you are observing in Elmah is generally a good thing because you don't want a diagnostic platform to cause problems that may necessitate other diagnostics. That's why Elmah or logging frameworks don't throw, and that's why you should make the exception rethrowing mechanism triggerable so your program doesn't have to watch its step when raising exceptions in Elmah.
No, no no! Never display the connection string to the user and never tell them what the problem is. Doing so is a serious security vulnerability. Simply put, don't do it. Fix your underlying problems with Elmah.
Problems in your error handling pipeline are very bad, because it'll cause it to try to handle the new error that's generated, which basically causes a loop. The ASP.NET engine recognizes that something serious has gone wrong, so it gives a generic "the service is unavailable" message. Check the event logs on your server to find out the underlying Elmah error and correct it.

Catching Exception message from Boolean method

I have seen similar questions, but not exactly this:
I would like to know the right way of determining whether a method is executed correctly or not, returning a boolean, and if the method is not executed know the reason, even if an exception is thrown.
I do it in this way, but I think that return inside the catch is a bad practice, so which is the right way?:
if(!myObject.DoSomething('A', out result))
{
MessageBox.Show(myObject.ErrorMessage);
[...]
}else{
MessageBox.Show(result);
[...]
}
class myObject()
{
public string ErrorMessage;
bool DoSomething(char inputValue, out string result)
{
try
{
if(inputValue == 'A')
{
ErrorMessage = "Bad input value: " + inputValue;
return false;
}
[...]
return true;
}catch(Exception ex){
ErrorMessage = ex.Message;
return false;
}
}
I don't like trhow the exception inside the catch because I lose the control of the application (and I can't get the description), and the exception always finish in the form. And if I show the exception in the form, I don't need try catch in the rest of the classes.
I mean that try {} catch(Exception ex) { throw ex;} is the same as not putting try catch.
thanks a lot
My suggestion would be to create your own Exception type (possibly global), and pass it in as a reference.
Thereafter you can still get back your boolean indicating success or failure (and having only one return outside of the try..catch).
public class CustomException
{
private string _message;
private string _title;
public CustomException()
{
_title = "";
_message = "";
}
public CustomException(string title, string message)
{
_title = title;
_message = message;
}
}
Then call DoSomething passing in an instance of CustomException (ce in this case).
CustomException ce = new CustomException();
Be advised this is the best process to solve the problem of having to return a boolean indicating success or failure and know the message, for example; dumping it to a log file or logging to database (particularly for Service Calls - WCF)
However this is not a solution for bad logic in handling business process.
Return false inside a catch isn't by itself bad practice. It's useful when you handle a piece of code's exceptions and it must not fail.
For example, I'm working on a printer piloting DLL at the time, and this DLL must read a XML file containing multiple records to print. The method must not fail because one record fails to print, but it still can return exception if the XML file is not correctly formated.
public void Print(string xmlFile)
{
if (String.IsNullOrWhiteSpace(xmlFile))
throw new ArgumentNullException("No xml file has been passed to the Print method.");
// This line will most likely throw an exception if the XMl file is not well formated
XDocument dom = XDocument.Load(xmlFile);
foreach (XElement n in dom.XPathSelectElements("//RECORDS/RECORD"))
{
try
{
// send commands to the printer, if the printer fails to print, throw a PrinterRecordException
}
catch (PrinterRecordException e)
{
// log print failure, but keep on printing the rest
continue;
}
catch (Exception e)
{
// dunno what happened, but still have to print the rest
continue;
}
}
}
In this example, my function could return false instead of throwing exceptions to the main program, if this program doesn't care. In my case it does :p In my opinion, that's how you should think your method.
Exception handling methods and best practices are a some-what subjective matter. I cannot attest to the method I'm about to present because I have only just started to use it in my own project.
What I suggest is having a static ExceptionHandler class with which you can register any exception to be handled by Generic Parameter and its corresponding handler. This will decouple your business logic from your UI in case you wanted to display some kind of message box when a particular exception occurs.
Here's an example:
/// the real implementation uses lambda's and/or implementations of IExceptionHandler<TException>
ExceptionHandler.Register<InvalidPasswordException>(() => /*some handler logic*/);
// ... else where in the code ...
catch (InvalidPasswordException ex)
{
// do resource clean-up and raise exception for listeners such as the UI or logging infrastructure.
ExceptionHandler.Raise(ex);
}
So far this looks promising, especially when compared with my previous approaches. But only time will tell.
Update
The ExceptionHandler class itself need not be static, for example you might want to have different instances of ExceptionHandlers at different layers of your application if you are using a layered architecture.

When to Throw an Exception? When to Handle an Exception (Service Layer, Controller) where?

I rewritten my question as I think it was too wordy and maybe what I am trying to achieve was lost.
I written this code in notepad so it may have mistakes and some stuff maybe not well thoughout but it is to illustrate what I see my options are.
// I wrap all code send back from service layer to controller in this class.
public class ResponseResult
{
public ResponseResult()
{
Errors = new Dictionary<string, string>();
Status = new ResponseBase();
}
public void AddError(string key, string errorMessage)
{
if (!Errors.ContainsKey(key))
{
Errors.Add(key, errorMessage);
}
}
public bool IsValid()
{
if (Errors.Count > 0)
{
return false;
}
return true;
}
public Dictionary<string, string> Errors { get; private set; }
public ResponseBase Status { get; set; }
}
public class ResponseResult<T> : ResponseResult
{
public T Response { get; set; }
}
public class ResponseBase
{
public HttpStatusCode Code { get; set; }
public string Message { get; set; }
}
Option 1 (what I am using now)
//controller
public HttpResponseMessage GetVenue(int venueId)
{
if (venueId == 0)
{
ModelState.AddModelError("badVenueId", "venue id must be greater than 0");
if (ModelState.IsValid)
{
var venue = venueService.FindVenue(venueId);
return Request.CreateResponse<ResponseResult<Venue>>(venue.Status.Code, venue);
}
// a wrapper that I made to extract the model state and try to make all my request have same layout.
var responseResult = new ResponseResultWrapper();
responseResult.Status.Code = HttpStatusCode.BadRequest;
responseResult.Status.Message = GenericErrors.InvalidRequest;
responseResult.ModelStateToResponseResult(ModelState);
return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);
}
// service layer
public ResponseResult<Venue> FindVenue(int venueId)
{
ResponseResult<Venue> responseResult = new ResponseResult<Venue>();
try
{
// I know this check was done in the controller but pretend this is some more advanced business logic validation.
if(venueId == 0)
{
// this is like Model State Error in MVC and mostly likely would with some sort of field.
responseResult.Errors.Add("badVenueId", "venue id must be greater than 0");
responseResult.Status.Code = HttpStatusCode.BadRequest;
}
var venue = context.Venues.Where(x => x.Id == venueId).FirstOrDefault();
if(venue == null)
{
var foundVenue = thirdPartyService.GetVenue(venueId);
if(foundVenue == null)
{
responseResult.Status.Code = HttpStatusCode.NotFound;
responseResult.Status.Message = "Oops could not find Venue";
return responseResult;
}
else
{
var city = cityService.FindCity(foundVenue.CityName);
if(city == null)
{
city = cityService.CreateCity(foundVenue.CityName);
if(city.Response == null)
{
responseResult.Status.Code = city.Status.Code;
responseResult.Status.Message = city.Status.Message;
return responseResult;
}
CreateVenue(VenueId, city.Response, foundVenue.Name);
responseResult.Status.Code = HttpStatusCode.Ok;
// I don't think I would return a success message here as the venue being displayed back to the user should be good enough.
responseResult.Status.Message = "";
reponseResult.Response = foundVenue;
}
}
return responseResult;
}
}
catch (SqlException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
// maybe roll back statement here depending on the method and what it is doing.
}
// should I catch this, I know it should be if you handle it but you don't want nasty messages going back to the user.
catch (InvalidOperationException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
}
// should I catch this, I know it should be if you handle it but you don't want nasty messages going back to the user.
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
}
return responseResult;
}
// another service layer.
// it is ResponseResult<City> and not city because I could have a controller method that directly calls this method.
// but I also have a case where my other method in another service needs this as well.
public ResponseResult<City> CreateCity(string CityName)
{
ResponseResult<City> responseResult = new ResponseResult<City>();
try
{
City newCity = new City { Name = "N" };
context.Cities.Add(newCity);
context.SaveChanges();
responseResult.Status.Code = HttpStatusCode.Ok;
responseResult.Status.Message = "City was succesfully added";
}
// same catch statmens like above
catch (SqlException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
// maybe roll back statement here depending on the method and what it is doing.
}
return responseResult;
}
As you can see the methods are all wrapped in the status codes as they could be directly called by the controller being public. FindCity() and CreateVenue() could also have this wrapping.
Option 2
public HttpResponseMessage GetVenue(int venueId)
{
try
{
if (venueId == 0)
{
ModelState.AddModelError("badVenueId", "venue id must be greater than 0");
if (ModelState.IsValid)
{
var venue = venueService.FindVenue(venueId);
return Request.CreateResponse<ResponseResult<Venue>>(HttpSatusCode.Ok, venue);
}
// a wrapper that I made to extract the model state and try to make all my request have same layout.
var responseResult = new ResponseResultWrapper();
responseResult.Status.Code = HttpStatusCode.BadRequest;
responseResult.Status.Message = GenericErrors.InvalidRequest;
responseResult.ModelStateToResponseResult(ModelState);
return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);
}
catchcatch (SqlException ex)
{
// can't remember how write this and too tried to look up.
return Request.CreateResponse(HttpStatusCode.InternalServerError;, "something here");
}
}
public Venue FindVenue(int venueId)
{
try
{
// how to pass back business logic error now without my wrapper?
if(venueId == 0)
{
// what here?
}
var venue = context.Venues.Where(x => x.Id == venueId).FirstOrDefault();
if(venue == null)
{
var foundVenue = thirdPartyService.GetVenue(venueId);
if(foundVenue == null)
{
// what here?
}
else
{
var city = cityService.FindCity(foundVenue.CityName);
if(city == null)
{
city = cityService.CreateCity(foundVenue.CityName);
if(city == null)
{
// what here?
}
CreateVenue(VenueId, city.Response, foundVenue.Name);
}
}
return venue;
}
}
catch (SqlException ex)
{
// should there be a try catch here now?
// I am guessing I am going to need to have this here if I need to do a rollback and can't do it in the controller
// throw exception here. Maybe this won't exist if no rollback is needed.
}
return null;
}
public City CreateCity(string CityName)
{
// if it crashes something I guess will catch it. Don't think I need to rollback here as only one statement being sent to database.
City newCity = new City { Name = "N" };
context.Cities.Add(newCity);
context.SaveChanges();
return newCity;
}
As you see with option 2, I might still need to wrap it in try catches for rollbacks and I am not sure how to handle advanced business validation.
Also with catching everything in the controller and sending back vanilla objects(without my wrapper) I am unsure how to do fine grain HttpStatus codes(say like notFound,Create and such)
Sorry for the brief response, but here is my general rule - if an exception occurs which you expect might happen, deal with it - either by retrying or telling the user something went wrong and giving them options to fix it.
If an unexpected exception occurs, if it's something you can deal with (e.g a timeout which you can retry) try to deal with it, otherwise get out - just think what any MS app does - e.g. office - you get an apology that something went wrong and the app ends. It's better to end gracefully than to potentially corrupt data and leave things in a real mess.
This is an article with Java-specific concepts and examples, but the broad principles here are the way to go.
Distinguish between fault exceptions, which are catastrophic and unrecoverable, and contingency exceptions, which are very much recoverable. Let the faults "bubble" to the fault barrier, where you handle appropriately. For example, you might log the error, E-mail someone or send a message to a message queue, and present the user with a nice, informative error page.
Whatever you do, be sure to preserve all the exception information from the source.
Hope that helps.
Throw an exception wherever your code determines that something has gone wrong.
You always need to handle exceptions in methods which are called directly by the end-user. This is to cater for unexpected errors which your code doesn't have specific handling for. Your generic handling code would typically log the error and may or may not include letting the user know that an unexpected error has occurred.
But if there are errors which you can expect ahead of time, you'll often want to handle these lower down in the code, nearer to the point at which they occur, so that your application can "recover" from the error and continue.
I think exceptions are useful any time you need to return details of a failure from a method, whilst being able to use the ideal return type for the method you're calling.
You said in your question:
Now for me I try to return error messages back to the the controller
and try not to really catch anything in the controller.
If the service method is supposed to ideally return a Venue object, how do you return this potential error message back to the controller? an out parameter? change the return type to something which has an error message property on it?
If you're doing either of those options, I think you're reinventing the wheel... i.e. creating a way to return exception information when one already exists.
Finally, Exceptions are strongly typed representations of what went wrong. If you return an error message, then that is fine to send back to the user, but if you need to programatically do different things based on the details of the error, then you don't want to be switching on magic string.
For example, wouldn't it be handy to differentiate between authorization errors and not found errors so you can return the most appropriate http status code to the user?
Don't forget that the Exception class has a Message property you can simply return to the user if you want to use it that way
To make sure I understand the question, your are creating a web service and want to know when to handle and when to throw exceptions.
In this situation I would strongly recommend that you catch all exceptions. "Unhandled" exceptions are very bad form. On web sites they result in displays that range from meaningless to dangerous by exposing internal information that you do no want the public to see.
If this is a good sized program I suggest that you create your own MyException class which derives from System.Exception. The purpose of this is provide a place for you to add additional information specific to your application. Here are some typical things I like to add to my MyException classes:
An ID number that will help me find the location in the code where the problem occurred.
A "LogMessage" method that logs the exception, sometimes to the Windows Event Log. Whether or not you log and to which log you write depends on what you want recorded, and the severity of the situation.
An indicator that shows the exception has been logged so the above method will not log twice even if it gets called more than once.
Anything else that might be useful given the circumstance.
I also like to put the text of the messages in an external resource file, like an XML document, and key them to the error number that you assign. This allows you to change the error text to improve clarity without having to redeploy the application.
Catch all exceptions and create a new instance of your MyException type and put the original exception into inner exception property. Below the first level of my application, I always throw one of my MyException instances rather than the original exception.
At the top level (application level), NEVER let an exception go unhandled and never throw your own exception. A better way is to return an error code and message in your data contract. That way the client application will only get what you want them to see. The only exceptions they'll need to worry about are the ones outside your scope, i.e. configuration errors or communication failures. In other words if they are able to invoke your service and the network stays connected you should give them a response they can interpret.
Hope this helps.
PS I didn't include a sample exception as I am sure a little searching will find many. Post if you want me to put up a simple sample.
Use try catch at all levels and bubble it up. Optionally, log the error in a file or database. I use text file - tab delimited. Capture at each level
1. Module Name (Use C# supplied methods to get this)
2. Method Name
3. Code Being Executed (User created - "Connecting to database")
4. Error Number
5. Error Description
6. Code Being Executed (User created - "Accessing database")
7. Error Number for the end user
8. Error Description for the end user
Additionally, I also pass a unique identifier like - Session Id in case of Web, Logged in User Id, User Name (if available)
I always have the Exception catch block. In here I set the error number as -0 and the message from the exception object as the error description. If it is SQL Server related - I capture SQL Exception. This generates an error number - I use that.
I want to extend this some more though.

DbEntityValidationException - How can I easily tell what caused the error?

I have a project that uses Entity Framework. While calling SaveChanges on my DbContext, I get the following exception:
System.Data.Entity.Validation.DbEntityValidationException: Validation
failed for one or more entities. See 'EntityValidationErrors' property
for more details.
This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors.
How can I see the details hidden within the DbEntityValidationException?
The easiest solution is to override SaveChanges on your entities class. You can catch the DbEntityValidationException, unwrap the actual errors and create a new DbEntityValidationException with the improved message.
Create a partial class next to your SomethingSomething.Context.cs file.
Use the code at the bottom of this post.
That's it. Your implementation will automatically use the overriden SaveChanges without any refactor work.
Your exception message will now look like this:
System.Data.Entity.Validation.DbEntityValidationException: Validation
failed for one or more entities. See 'EntityValidationErrors' property
for more details. The validation errors are: The field PhoneNumber
must be a string or array type with a maximum length of '12'; The
LastName field is required.
You can drop the overridden SaveChanges in any class that inherits from DbContext:
public partial class SomethingSomethingEntities
{
public override int SaveChanges()
{
try
{
return base.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);
}
}
}
The DbEntityValidationException also contains the entities that caused the validation errors. So if you require even more information, you can change the above code to output information about these entities.
See also: http://devillers.nl/improving-dbentityvalidationexception/
As Martin indicated, there is more information in the DbEntityValidationResult. I found it useful to get both my POCO class name and property name in each message, and wanted to avoid having to write custom ErrorMessage attributes on all my [Required] tags just for this.
The following tweak to Martin's code took care of these details for me:
// Retrieve the error messages as a list of strings.
List<string> errorMessages = new List<string>();
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
string entityName = validationResult.Entry.Entity.GetType().Name;
foreach (DbValidationError error in validationResult.ValidationErrors)
{
errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
}
}
To view the EntityValidationErrors collection, add the following Watch expression to the Watch window.
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
I'm using visual studio 2013
While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.
For Visual 2012+ users who care only about the first error and might not have a catch block, you can even do:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
To quickly find a meaningful error message by inspecting the error during debugging:
Add a quick watch for:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
Drill down into EntityValidationErrors like this:
(collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage
Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database.
So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20.
Or, in other cases, if the column does not allow to be a Null.
So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it.
I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues
I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.
I would prefer to create an extension method. More reasons to this:
Keep original stack trace
Follow open/closed principle (ie.: I can use different messages for different kind of logs)
In production environments there could be other places (ie.: other dbcontext) where a DbEntityValidationException could be thrown.
For Azure Functions we use this simple extension to Microsoft.Extensions.Logging.ILogger
public static class LoggerExtensions
{
public static void Error(this ILogger logger, string message, Exception exception)
{
if (exception is DbEntityValidationException dbException)
{
message += "\nValidation Errors: ";
foreach (var error in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
{
message += $"\n * Field name: {error.PropertyName}, Error message: {error.ErrorMessage}";
}
}
logger.LogError(default(EventId), exception, message);
}
}
and example usage:
try
{
do something with request and EF
}
catch (Exception e)
{
log.Error($"Failed to create customer due to an exception: {e.Message}", e);
return await StringResponseUtil.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}
Use try block in your code like
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
You can check the details here as well
http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
http://blogs.infosupport.com/improving-dbentityvalidationexception/

simplify my groupby

hi i would like to return the group data back to the ui layer.
here is how i want to do a simplify the groupby "GenerationDate" and return the data in List<> back to UI gridview.
i find it very troublesome as i got to do the forloop. Also in the UI layer i got to do another forloop for this simple groupby. Could you help to simplify it?
public List<SalaryTracker> GetSalaryTrackerOrderByGenerationDate(int tutorId)
{
List<SalaryTracker> salary = new List<SalaryTracker>();
using (leDataContext db = new leDataContext())
{
try
{
var r =
from s in db.SalaryTrackers
where s.StaffId == 2 && s.PaymentDate == null
group s by s.GenerationDate into g
where g.Count() > 0
select new
{
date = g.Key, totalSalary = g.Sum(p => p.SalaryAmount)
};
foreach (var rr in r)
{
SalaryTracker m = new SalaryTracker();
m.GenerationDate = rr.date;
m.SalaryAmount = rr.totalSalary;
salary.Add(m);
}
return salary;
}
catch (Exception ex)
{
Logger.Error(typeof(SalaryTracker), ex.ToString());
throw;
}
}
}
--------------- GUI
totalCommissionsGroup = salary.GetSalaryTrackerOrderByGenerationDate(tutor.Id);
IList<SalaryTracker> rr = (
totalCommissionsGroup.GroupBy(x => x.GenerationDate)
.Select(g => new SalaryTracker
{
MonthId = g.Key.Month,
MonthToPay = common.GetMonthName(Convert.ToInt16(g.Key), true),
SalaryAmount = g.Sum(x => x.SalaryAmount)
})).ToList<SalaryTracker>();
gvSalaryPayment.DataSource = rr;
i do this so that i can get the MonthToPay in string
public List<SalaryTracker> GetSalaryTrackerOrderByGenerationDate(int tutorId)
{
using (var db = new leDataContext())
{
try
{
return (
from s in db.SalaryTrackers
where s.StaffId == 2 && s.PaymentDate == null
group s by s.GenerationDate into g
select new
{
MonthId = g.Key.Month,
// I don't know what "common" is in your UI code,
// I am just using GetMonthName here
MonthToPay = GetMonthName(Convert.ToInt16(g.Key), true),
SalaryAmount = g.Sum(p => p.SalaryAmount)
})
.AsEnumerable()
.Select(x => new SalaryTracker
{
MonthId = x.MonthId,
MonthToPay = x.MonthToPay,
SalaryAmount = x.SalaryAmount
})
.ToList();
}
catch (Exception ex)
{
Logger.Error(typeof(SalaryTracker), ex.ToString());
throw;
}
}
}
I agree with the refactoring of Mahesh Velaga (+1 for that) and I like to add that logging errors at that level of the application is unusual. Especially when you decide to rethrow the exception any way. Therefore, I suggest that you remove the complete try catch with error logging and log only in the root of your application (if you're not already doing that). That makes your code much more cleaner.
When you've done that, you'll see that what's left is a nice readable method with hardly anything else than business logic.
UPDATE
But if we do not put the 'try catch'
in the datamodel layer, how would the
main caller catch the error? i have
been using this pattern for years..
please correct me if i am wrong. Refer
to this link.
Catching the way you do in your question or is done as is shown in the referenced article you provide is almost always sub optimal, because of several reasons:
Catching, logging and rethrowing at the service layer is unfortunate, because you will end up with double entries of this error in your logging system, simply, because you need to log at the top layer of your application anyway, because otherwise you will miss logging errors that do not originate from the service layer. Ignoring the error (by not rethrowing it) is also a bad idea, because the client should hardly ever continue when an error occurs.
Catching at the presentation layer as shown in the referenced article is also unfortunate, because this way you don't log the errors, but more importantly, you present the user with possibly technical and obscure error messages (perhaps even in a foreign language) that they don't understand and it will frustrate them. Even worse, it could lead to information leakage that allows hackers to see what going on under the surface when attacking your application (in case of a publicly exposed web application).
This doesn't mean that you can't display any error information to the users, but only do that for exceptions that you thrown explicitly to present error information for the users. For instance:
try
{
// Call into service layer
}
catch (BusinessLayerException ex)
{
this.ValidationSummary1.Add(new CustomValidator
{
ErrorMessage = ex.Message, IsValid = false
});
}
In this example, the BusinessLayerException is a special exception that is thrown from the business layer that contains error messages that are understandable for the user (possibly with a localized error message if your application is used by users of multiple languages).
For all other exceptions, most of the time you don't want to show the user that exact error message, because you have no idea what went wrong and how severe the error is and what information the exception contains. The best thing to do is to have as less error handling logic as possible in your presentation layer, and handle this at one place in the top layer of the application. Here you ensure that an error page is displayed to the user in that case and you ensure that the error is logged to the logging system.
You can configure ASP.NET to show a custom error page in case of an error. Here's an example:
<customErrors mode="RemoteOnly"
defaultRedirect="~/ErrorPage.htm">
</customErrors>
The ErrorPage.htm can display general information like the general "it's our fault" error page here at Stackoverflow. Perhaps some contact information of support, your home phone number, so they can call you at night ;-)
By implementing the Application_Error method in the global.asax, you can at a single place in the application log unhandled exceptions:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// Log the exception here.
}
Make sure you log al the information about the error you need, such as stack trace, error message, exception type, and all the inner exceptions that can occur.
I hope this helps.

Categories

Resources