Search code examples
c#visual-studiodebuggingexceptionwindow

How do I control the message shown in the "Exception Thrown" window in C#?


I have a custom exception type derived from System.Exception called ErrorCodeException. It has an "ErrorCode" property, that I'd like to display when debugging. The problem is, the window only shows the "Message" property of the base type.

enter image description here

The aim would be to display this ToString() function's return value:

public override string ToString()
{
   return $"Error code: {(int)ErrorCode} - {ErrorCode.ToString()} Message: {Message}";
}

The full declaration of my custom exception type:

[System.Diagnostics.DebuggerDisplay("{ToString()}")]
public class ErrorCodeException : Exception
{
    public ErrorCode ErrorCode { get; private set; }

    public ErrorCodeException(ErrorCode errorCode, string message) : base(message)
    {
        this.ErrorCode = errorCode;
    }

    public ErrorCodeException(ErrorCode errorCode) : base()
    {
        this.ErrorCode = errorCode;
    }

    public override string ToString()
    {
        return $"Error code: {(int)ErrorCode} - {ErrorCode.ToString()} Message: {Message}";
    }
}

Solution

  • Implementing ToString() solves this, since it we'll be shown in the debug console, on complex objects.