0

In C#, how do I throw a Custom Exception that contains the Stack Trace? The Call Stack would also work for my logging requirements.

The custom exception is defined like this...

public class UserNameRequiredExcp : Exception
{
    public UserNameRequiredExcp() : base() { ExceptionLogging.WriteToLog(this); }
    public UserNameRequiredExcp(string message) : base(message) { ExceptionLogging.WriteToLog(this); }
    public UserNameRequiredExcp(string message, Exception exception ) : base(message, exception) { ExceptionLogging.WriteToLog(this); }
}

It is thrown like this ...

public void SetUserName(string userName)
{

    if (String.IsNullOrEmpty(userName)) 
    { throw new UserNameRequiredExcp(); }

    _userName = userName;
} 

When the ExceptionLogging method executes the stack trace is null?

internal static void WriteToLog(Exception exception)
{
    string stackTrace = exception.StackTrace;
}
vscoder
  • 929
  • 1
  • 10
  • 25
  • The referenced question talks about when the Stack Trace can be null, and from that discussion I was able to determine that the Stack Trace is only populated within the Catch block. The constructor for the Custom Exception does not have access to the Stack Trace, only the Catch block will have that. – vscoder Jul 19 '19 at 16:57

1 Answers1

1

The problem is: stack trace is being retrieved inside constructor. It'll always be null there. Stack trace is populated at the time exception is being thrown, not before it.

It's better to do logging somewhere in caller hierarchy, not in exception itself. Because exceptions are data, e.g. if there will be a cross domain call, exception will be serialized-deserialized, so constructor will be called second time (in your example there will be 2 log records for single exception)

Renat
  • 7,718
  • 2
  • 20
  • 34