-1

My below code is not able to tackle null reference, even though I tried different ways:

Exception ex = null;
ex = Server.GetLastError();
if (ex.InnerException.Message.Contains("Network Transport").ToString() != null)
{
    Response.Redirect("~/TestError.aspx");
}

Error after trying below code:

bool? hasError = ex?.InnerException?.Message?.Contains("Network Transport");
if (hasError.HasValue && hasError.Value)
{
    Response.Redirect("~/TestError.aspx");
}

enter image description here

Ivan Shumilin
  • 1,743
  • 3
  • 13
  • 18
VimalSingh
  • 237
  • 2
  • 4
  • 16

1 Answers1

2

I would write your code in this way:

Exception ex = Server.GetLastError();
bool? hasError = ex?.InnerException?.Message?.Contains("Network Transport");
if (hasError.HasValue && hasError.Value)
{
    Response.Redirect("~/TestError.aspx");
}

You cannot convert a boolean to a string and then check for null. Just use the boolean.
Actually, even if we take for granted that ex is not null, InnerException is not null and Message is not null, Contains returns a boolean and converting it to a string gives "true" or "false" so the if condition is never true.

So you should really add the Null Conditional Operator to defend yourself by a Null Reference Exception if any of the inner objects is null and use the resulting nullable boolean to check if you need to redirect or not

In case your current C# language version doesn't support the Null Conditional Operator (confusing called also Null Propagation Operator) you need to apply a nested if logic

if (ex != null && 
    ex.InnerException != null && 
    ex.InnerException.Message != null) 
  if(ex.InnerException.Message.Contains("Network Transport"))
      Response.Redirect("~/TestError.aspx");

but you should really upgrade the language version instead...

Steve
  • 213,761
  • 22
  • 232
  • 286
  • your code i tried but its giving error like 'null propagating operator'.I am attaching error in the image with my question. – VimalSingh Aug 23 '22 at 14:33
  • 1
    Well, the error message is clear. You need to use C# 6.0, you are using C# 5.0 . If you are using Visual Studio 2019 then there is an answer here on upgrading the language https://stackoverflow.com/questions/60247122/changing-the-c-sharp-version-in-visual-studio-2019#:~:text=%20The%20simplest%20way%20to%20change%20C%23%20language,all%20possible%20c%205%20%20versions.%20More%20 – Steve Aug 23 '22 at 15:32