using BuddyFinance.Integration.Logging; using BuddyFinance.Integration.Models; using BuddyFinance.Integration.Models.Enums; using System.Data.Entity.Validation; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http.Filters; namespace BuddyFinance.WebApi.Filters { /// /// /// public class LogExceptionAttribute : ExceptionFilterAttribute { /// /// /// /// public override void OnException(HttpActionExecutedContext actionExecutedContext) { var exceptionStr = new StringBuilder(); if (actionExecutedContext.Exception is DbEntityValidationException) { foreach (var entityValidationError in ((DbEntityValidationException)actionExecutedContext.Exception).EntityValidationErrors) { exceptionStr.AppendLine($"Entity of type \"{entityValidationError.Entry.Entity.GetType().Name}\" in state \"{entityValidationError.Entry.State}\" has the following validation errors:"); foreach (var ve in entityValidationError.ValidationErrors) { exceptionStr.AppendLine($"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\""); } } exceptionStr.AppendFormat(actionExecutedContext.Exception.ToString()); } else { exceptionStr.AppendFormat(actionExecutedContext.Exception.ToString()); } var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; var contoller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; Logger.Log( LogTypeEnum.Error, $"Error Excecuting action '{action}' in controller '{contoller}', Exception: '{actionExecutedContext.Exception.Message}. \n\n {exceptionStr}'", null, actionExecutedContext.ActionContext.Request.GetOwinContext().Request.RemoteIpAddress, actionExecutedContext.ActionContext.Request.Headers.UserAgent.ToString()); var result = new BaseResult { ErrorCode = (int)ResponseCodes.Exception, ErrorMessage = actionExecutedContext.Exception.Message, Result = null }; actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result); //base.OnException(actionExecutedContext); } } }