0

I have following code and getting warning by sonaqube at line

Unable to understand what's the problem or what correction i should do

 public static Exception ExceptionProcessingForHttpTypeRequest(Exception ex)
        {
            if (ex.InnerException is TimeoutException)
            {
                ex = ex.InnerException;
            }
            else if (ex is TaskCanceledException)
            {
            
               //Change this condition so that it does not always evaluate to 'false'.
                if ((ex as TaskCanceledException).CancellationToken == null || !(ex as TaskCanceledException).CancellationToken.IsCancellationRequested)

                {
                    ex = new TimeoutException("Task Canceled due to Timeout");
                }
                else if (ex.InnerException != null)
                {
                    ex = new Exception("TaskCanceled Inner exception," + ex.InnerException.Message, ex.InnerException);
                }
            }
            return ex;
        }
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
  • Why are you using the older `x is {Type}` operator instead of the newer (and better) `x is {Type} name` operator? – Dai Feb 17 '22 at 10:16
  • The message is because `CancellationToken` is a `struct`, so it can never be `null`. Also, your logic in that `if` statement is incorrect: you should be testing for `OperationCanceledException` (from which `TaskCanceledException` derives) and the condition is the opposite: if `ex.CancellationToken.IsCancellationRequested == true` then **it is** due to a timeout. – Dai Feb 17 '22 at 10:16
  • Thanks Dai. can you please give answer with the edit you are mentioning. – Kamran Shahid Feb 17 '22 at 10:26
  • What is `ExceptionProcessingForHttpTypeRequest` _meant_ to be doing? The name of the method doesn't suggest it has anything to do with checking for timeouts specifically, so why is it doing that? Why are you creating new `Exception` instances? I don't want to tell you to _just_ change the `if` condition because I think there are bigger, more fundamental problems, with your code as-is. – Dai Feb 17 '22 at 10:34
  • May be name can be change. problem was during http post/get/ async i was getting timeout and on backend i wanted to send some appropriate exception messages – Kamran Shahid Feb 17 '22 at 10:43
  • related question https://stackoverflow.com/questions/29179848/httpclient-a-task-was-cancelled – Kamran Shahid Feb 17 '22 at 10:46
  • @Dai what i understand is i should remove (ex as TaskCanceledException).CancellationToken == null || – Kamran Shahid Feb 18 '22 at 11:08

0 Answers0