I recently tried setting up a logging system for my Web API. I decided that I wanted to create custom Exception classes that could be thrown and then logged by my GlobalExceptionHandler. However, I am having some issues accessing the StackTrace of my custom Exception objects.
I set up a custom Exception class called LoggableException which I use as a parent class for all of my custom Exceptions that I want to log to my database.
public class LoggableException : Exception
{
public LogEntity Log { get; set; }
public string ResponseMessage { get; set; }
public LoggableException(LogEntity _log, string _responseMessage) : base(_log.ExceptionMessage)
{
Log = _log;
Log.Level = LogLevel.Warn;
Log.Exception = GetType().Name;
Log.StackTrace = StackTrace.Substring(0, 1000);
ResponseMessage = _responseMessage;
}
}
Here is an example of one of my custom LoggableExceptions:
public class InvalidPassword : LoggableException
{
public InvalidPassword(string email) : base(new LogEntity()
{
ExceptionMessage = $"Invalid password. email: {email}",
ResponseCode = (int) HttpStatusCode.Unauthorized
}, $"Unknown email or incorrect password.")
{ }
}
However, it seems that whenever I throw one of these LoggableExceptions, a <System.NullReferenceException: Object reference not set to an instance of an object. is also thrown at Log.StackTrace = StackTrace.Substring(0, 1000);. I'm doing this so that I don't store huge StackTrace strings in my database, but StackTrace is always null. I assumed that if I called the base constructor that it would automatically instantiate StackTrace, but I guess I was wrong. Can anyone explain to me what I am doing wrong here? I am still relatively new to C#.
StackTraceclass if you want), don't make the exception do it.