0

I have a simple function to log errors that might happen when displaying certain pages. I'm using the the null coalescing operator to make sure I dont have any null's in my string.Format. Yet, I still see these errors in the event log:

Error: System.NullReferenceException: Object reference not set to an instance of an object.
   at ASP._core_showad_aspx.LogError(String sType, String sIP, Nullable`1 id, Nullable`1 id2)
void LogError(string sType, string sIP, int? id, int? id2)
{
    string error   =   string.Format("'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}'", 
    sType??"", sIP??"", id??-1, id2??-1, 
    Request.ServerVariables["HTTP_X_ORIGINAL_URL"]??"", Request.ServerVariables["URL"]??"", Request.ServerVariables["QUERY_STRING"]??"", 
    Request.Path??"", Request.ServerVariables["HTTP_REFERER"]??"", Request.ServerVariables["HTTP_USER_AGENT"]??"", 
    Request.ServerVariables["REMOTE_HOST"]??"", Request.ServerVariables["HTTP_COOKIE"].Substring(0, (Request.ServerVariables["HTTP_COOKIE"].Length>399)?399:Request.ServerVariables["HTTP_COOKIE"].Length)??"");

    WriteLog(error);
}

Shouldn't the null coalescing operator prevent this from happening?

Cornwell
  • 3,084
  • 5
  • 41
  • 73
  • One of your variables is definitely null. Use the debugger, Luke! – dcastro Jul 18 '14 at 10:38
  • 1
    `Request.ServerVariables["HTTP_COOKIE"].Substring(...)` - where do you check null here? – Konrad Kokosa Jul 18 '14 at 10:39
  • 2
    Most of your `??` operators are not necessary because `string.Format` is happy with `null` references inside the parameter array it takes in. However, as other have said, you cannot call `.Substring(...)` on a `null` reference. – Jeppe Stig Nielsen Jul 18 '14 at 10:42

1 Answers1

4

Your Request.ServerVariables["HTTP_COOKIE"] isn't check for null.

Try this:

string httpCookie = string.Empty;
if (Request.ServerVariables["HTTP_COOKIE"] != null)
{
   httpCookie = Request.ServerVariables["HTTP_COOKIE"].Substring(0, (Request.ServerVariables["HTTP_COOKIE"].Length>399)?399:Request.ServerVariables["HTTP_COOKIE"].Length)
}
Jan Barta
  • 440
  • 2
  • 8
  • Indeed... Missed that one. Thanks. can only accept it in 10 mins – Cornwell Jul 18 '14 at 10:39
  • 1
    @Cornwell You could make an extension like `public static string Truncate(this string stringOrNull, int maxLength) { return stringOrNull == null || stringOrNull.Length <= maxLength ? stringOrNull : stringOrNull.Remove(maxLength); }` or similar. Use it like `Request.ServerVariables["HTTP_COOKIE"].Truncate();`. – Jeppe Stig Nielsen Jul 18 '14 at 10:46
  • @JeppeStigNielsen Thank you! – Cornwell Jul 18 '14 at 15:45