N
N
Nikita072021-07-01 12:58:49
ASP.NET
Nikita07, 2021-07-01 12:58:49

How to continue executing code after an exception is thrown?

Help me understand
There is the following code and the problem is that if the URL (passed as request) does not exist or it is not currently responding, then the program throws an Exception and ends the work, and I need the work to continue, those. Exception appeared, registered in the Logger, but the work continued as usual, how can this be done?

public async Task<AuctionRequest> ProcessBidRequest(BidRequestModel requestModel, string endpoint, string protocol)
        {
            try
            {
                var requestString = JsonConvert.SerializeObject(requestModel);

                using var request = new HttpRequestMessage(HttpMethod.Get, endpoint);
                {
                    request.Content = new StringContent(requestString, Encoding.UTF8, "application/json");
                }
                request.Headers.Add("x-openrtb-version", protocol);

                using var response = await _client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                    throw new BadResponseException(response.ReasonPhrase);

                var respString = await response.Content.ReadAsStringAsync();

                if (respString.Length == 0)
                    throw new ArgumentException("The response is empty string.");

                return new AuctionRequest(requestModel, JsonConvert.DeserializeObject<BidResponseModel>(respString), protocol);

            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
                throw ex;
            }
        }


The method itself is called when iterating over the array, here is the part of the code that is responsible for calling this method

int k = 0;
foreach (var advert in rtb_partners)
{
    string[] address = { //Список URL-адресов };
    bids[i++] = ProcessBidRequest(bidRequest, address[k++], protocolVersion);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-07-01
@Nikita07

Do not throw in a catch block, or do a try-catch in a loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question