user1702369
user1702369

Reputation: 1161

Method throws Error instead of Returning null.Why?

I sometimes get an error:

There is not a header with name UserName and namespace http://www.website.com/ in the message.

Stacktrace

System.ServiceModel.Channels.MessageHeaders.GetHeader[T](String name, String ns, String[] actors) Common.Utilities.WCF.WcfCallContext.TryGetHeader(String key) Common.Utilities.WCF.WcfCallContext.get_UserName()

Here is the 2 Methods:

    private static string TryGetHeader( string key )
    {
        try
        {
            return GetHeader( key );
        }
        catch
        {
            return null;
        }
    }

    private static string GetHeader( string key )
    {
        var headers = OperationContext.Current.IncomingMessageHeaders;
        var value = headers.GetHeader<string>( key, "http://www.website.com/", "Project" );
        return value;
    }
}

So TryGetHeader(with try and catch) is calling GetHeader. Obviously it breaks on the:

var value = headers.GetHeader<string>( key, "http://www.website.com/", "Project" );

Why is it then that TryGetHeader does not catch it as an error and not returning a null? It is as if it breaks in GetHeader and stops instead of throwing back in error in TryGetHeader?

Upvotes: 3

Views: 717

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062725

If you call TryGetHeader, then that exception will be caught. I strongly suspect you are seeing a "first chance exception", or seeing the exception in the IDE / debugger. That is a phantom: the exception is not really there (or rather, it will get caught in normal execution). Try turning down the exception handling options in the IDE.

Upvotes: 6

Related Questions