In a number of places in the code examples in this book, you may have seen Log error comments. In general, it is not only good practice to log errors, but it can also help you to track down bugs and improve the overall user experience of the users of your applications.
The easiest place to log errors to would be an Errors database and the minimum useful information fields that you'd want to store would include details of the current user, the time the error occurred, the exception message, the stack trace, and the assembly or area that it occurred in. This latter field can be found in the Module property of the exception's TargetSite property:
public Error(Exception exception, User createdBy) { Id = Guid.NewGuid(); Message = FlattenInnerExceptions(exception); StackTrace = exception.StackTrace; Area = exception.TargetSite.Module.ToString(); CreatedOn = DateTime.Now; CreatedBy = createdBy; }
Note the use of the custom FlattenInnerExceptions method that also outputs the messages from any inner exceptions that the thrown exception may contain. One alternative to building your own FlattenInnerExceptions method would be to simply save the ToString output of the exception, which will also contain details of any inner exceptions that it may contain, although it will also contain stack trace and other information as well.