Pat Hanks

Pat Hanks

  • 1.7k
  • 81
  • 1.3k

Need some help on the proper way to build & use an Exception class

Nov 11 2022 3:18 PM

Hi All,

I'm fairly new to using C# and have never attempted this before.  I am building a data access class for using Access as the database.  In the class file I have a couple differnt classes that all work fine.  But I wanted to have a way to log all exceptions from each of the classes so I created a class (below).  But I can't figure out how I can use it without having a create a new object in each of the classes, which defeats the shared exception log.  Is there a way to achieve this? 

 public class DBExceptions : IEquatable<DBExceptions>
    {
        private List<Exception> _exceptions = new List<Exception>();

        public DBExceptions()
        {
            this._exceptions = new List<Exception>(); 
        }

        public Exception LastException
        {
            get
            {
                if (_exceptions != null) 
                    { return _exceptions[_exceptions.Count]; }
                else 
                    { return null; }
            }
        }

        public void AddException(Exception exception)
        {
            _exceptions.Add(exception);
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (!(obj is DBExceptions objAsPart)) return false;
            else return Equals(objAsPart);
        }

        public bool Equals(DBExceptions other)
        {
            if (other == null) return false;
            return (this._exceptions.Equals(other._exceptions));
        }

        public override int GetHashCode()
        {
            //return PartId;
            return new { _exceptions}.GetHashCode();
        }
    }

 


Answers (1)