The Invisible Guard

They are called Guards or Validators. It’s their duty to keep your business logic safe. Invalid input values are rejected by throwing exceptions at the caller to notify him about his wrong-doing. Guards enforce the contracts of your API. If you fail to get past them, it’s your problem, not that of the author of said logic.

But do you really want to see them in the StackTrace of each exception they throw? They are not the reason an exception occured. They just contain the location where the exception originated. But the cause for the exception is the call to a method using the wrong parameter values.

Hide Guards in StackTraces

I first saw that code in a colleague’s project. But it is also documented on StackOverflow.

Create a custom Exception that will be thrown by your Guard class. Override the StackTrace property and remove all lines that are related to that Guard class before you return the trace.

public static class Guard
{
  [DebuggerStepThrough]
  public static void AssertNotNull(object param, string paramName)
  {
    if (param == null)
    {
      throw new GuardNotNullException(paramName);
    }
  }
}
public class GuardNotNullException : ArgumentNullException
{
  public GuardNotNullException(string paramName)
    : base(paramName)
  {
  }

  public override string StackTrace
  {
    get
    {
      var stacktrace = base.StackTrace
        .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
        .Where(l => !l.StartsWith("   at " + typeof(Guard).FullName));
      return string.Join(Environment.NewLine, stacktrace);
    }
  }
}

Hide Guards in the Debugger

With this little trick your Guards won’t show up in StackTraces. But you don’t want to step through them whenever you debug a method they guard either. After all they are not part of the logic of the method they just enforce the method’s invariants.
You might have noticed the DebuggerStepThroughAttribute on the AssertNotNull method. This attribute instructs the Visual Studio debugger to ignore this method completely.

It’s easy. It’s neat. It helps your developers and administrators to focus on the actual source of the problem instead of distracting them with the noise of your validation code.