How should I handle exceptions for API data requester? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to make HTTP POST web requestHttpClient.GetAsync(…) never returns when using await/asyncHow to safely call an async method in C# without awaitWhy shouldn't all functions be async by default?Why not inherit from List<T>?How do I handle async operations in Startup.Configure?Node.js Best Practice Exception Handling - After Async/AwaitHttpClient.SendAsync method exits without throwing exceptionHow to throw exception from async functionHow to properly implement error handling in async/await case
Are bags of holding fireproof?
What does 'tubeless ready' wheelset actually mean
What helicopter has the most rotor blades?
Can stored/leased 737s be used to substitute for grounded MAXs?
Are there any AGPL-style licences that require source code modifications to be public?
Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?
What is the ongoing value of the Kanban board to the developers as opposed to management
lm and glm function in R
How is an IPA symbol that lacks a name (e.g. ɲ) called?
Alternative to "rest in peace" (RIP)
Why these surprising proportionalities of integrals involving odd zeta values?
2 sample t test for sample sizes - 30,000 and 150,000
Should man-made satellites feature an intelligent inverted "cow catcher"?
Why do C and C++ allow the expression (int) + 4*5?
Trying to enter the Fox's den
Can I ask an author to send me his ebook?
Can the van der Waals coefficients be negative in the van der Waals equation for real gases?
Can gravitational waves pass through a black hole?
Are Flameskulls resistant to magical piercing damage?
Is there a way to convert Wolfram Language expression to string?
Is my guitar’s action too high?
Marquee sign letters
Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?
Can 'non' with gerundive mean both lack of obligation and negative obligation?
How should I handle exceptions for API data requester?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to make HTTP POST web requestHttpClient.GetAsync(…) never returns when using await/asyncHow to safely call an async method in C# without awaitWhy shouldn't all functions be async by default?Why not inherit from List<T>?How do I handle async operations in Startup.Configure?Node.js Best Practice Exception Handling - After Async/AwaitHttpClient.SendAsync method exits without throwing exceptionHow to throw exception from async functionHow to properly implement error handling in async/await case
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
How should I handle this exception for API data requester?
The Dostuff1,2,3 is 3 different functions that retrieves data from an API. This function is ran every minute. What I want to do is to catch the exception, but not stop the program, and rather let it retry on the next iteration. How should I solve this? I guess I shouldn't be using throw, but the code want me to return something.
public async Task<string> Dostuff1,2,3()
try
using (HttpResponseMessage result = await _httpClient.GetAsync(Adrdess))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
string data = await content.ReadAsStringAsync();
return data;
catch (Exception ex)
Console.WriteLine("Error");
throw;
c# async-await
add a comment |
How should I handle this exception for API data requester?
The Dostuff1,2,3 is 3 different functions that retrieves data from an API. This function is ran every minute. What I want to do is to catch the exception, but not stop the program, and rather let it retry on the next iteration. How should I solve this? I guess I shouldn't be using throw, but the code want me to return something.
public async Task<string> Dostuff1,2,3()
try
using (HttpResponseMessage result = await _httpClient.GetAsync(Adrdess))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
string data = await content.ReadAsStringAsync();
return data;
catch (Exception ex)
Console.WriteLine("Error");
throw;
c# async-await
1
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
Does this even compile?datashould be out of scope for return, since it is local to the "using" block.
– Fildor
Mar 22 at 14:15
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39
add a comment |
How should I handle this exception for API data requester?
The Dostuff1,2,3 is 3 different functions that retrieves data from an API. This function is ran every minute. What I want to do is to catch the exception, but not stop the program, and rather let it retry on the next iteration. How should I solve this? I guess I shouldn't be using throw, but the code want me to return something.
public async Task<string> Dostuff1,2,3()
try
using (HttpResponseMessage result = await _httpClient.GetAsync(Adrdess))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
string data = await content.ReadAsStringAsync();
return data;
catch (Exception ex)
Console.WriteLine("Error");
throw;
c# async-await
How should I handle this exception for API data requester?
The Dostuff1,2,3 is 3 different functions that retrieves data from an API. This function is ran every minute. What I want to do is to catch the exception, but not stop the program, and rather let it retry on the next iteration. How should I solve this? I guess I shouldn't be using throw, but the code want me to return something.
public async Task<string> Dostuff1,2,3()
try
using (HttpResponseMessage result = await _httpClient.GetAsync(Adrdess))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
string data = await content.ReadAsStringAsync();
return data;
catch (Exception ex)
Console.WriteLine("Error");
throw;
c# async-await
c# async-await
edited Mar 22 at 14:10
meJustAndrew
3,24342552
3,24342552
asked Mar 22 at 14:01
user10935587
1
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
Does this even compile?datashould be out of scope for return, since it is local to the "using" block.
– Fildor
Mar 22 at 14:15
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39
add a comment |
1
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
Does this even compile?datashould be out of scope for return, since it is local to the "using" block.
– Fildor
Mar 22 at 14:15
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39
1
1
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
Does this even compile?
data should be out of scope for return, since it is local to the "using" block.– Fildor
Mar 22 at 14:15
Does this even compile?
data should be out of scope for return, since it is local to the "using" block.– Fildor
Mar 22 at 14:15
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39
add a comment |
2 Answers
2
active
oldest
votes
If the return value is what concerns you, then you can return null or new Task<string>(() => string.Empty) since they basically mean that you have no data to return.
Now it depends if you have a project with clear requirements where you should always have a default value to return or some other data source if this one is not available, but if you just want the code to compile, you can have a simple return null; there.
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
add a comment |
Your code looks duplicated to me. Instead of making 3 different functions, you should rather have one with arguments:
public async Task<string> GetStringFromAPIAsync( string resource )
// check input
if( string.IsNullOrWhitespace(resource) ) throw new ArgumentException(nameof(resource));
using (HttpResponseMessage result = await _httpClient.GetAsync(resource))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
return await content.ReadAsStringAsync();
// Issue in your code: 'data' was out of scope for the return.
// string data = await content.ReadAsStringAsync();
// return data; <- "data" is not visible here!
Mind that I got rid of all the exception handling here, since from my POV, it should be done by the caller, which also gives you more flexibility.
For example: you could write another function for retry like so:
public async Task<string> GetStringFromAPIWithRetryAsync(string resource, int maxRetry)
// limit retry to 1 .. 100
for( int retry = Math.Min(Math.Max(1,maxRetry),100); retry > 0 ; retry--)
try
return await GetStringFromAPIAsync( resource );
catch(Exception ex) // Actually, you'd only catch exceptions where a retry makes sense.
if( retry > 0 )
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
else
throw;
If you just need a default in case of error, you could do this:
public async Task<string> GetStringFromAPIOrDefaultAsync(string resource, string defaultValue)
string returnValue = defaultValue;
try
returnValue = await GetStringFromAPIAsync( resource );
catch(Exception)
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
return returnValue;
}
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301295%2fhow-should-i-handle-exceptions-for-api-data-requester%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
If the return value is what concerns you, then you can return null or new Task<string>(() => string.Empty) since they basically mean that you have no data to return.
Now it depends if you have a project with clear requirements where you should always have a default value to return or some other data source if this one is not available, but if you just want the code to compile, you can have a simple return null; there.
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
add a comment |
If the return value is what concerns you, then you can return null or new Task<string>(() => string.Empty) since they basically mean that you have no data to return.
Now it depends if you have a project with clear requirements where you should always have a default value to return or some other data source if this one is not available, but if you just want the code to compile, you can have a simple return null; there.
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
add a comment |
If the return value is what concerns you, then you can return null or new Task<string>(() => string.Empty) since they basically mean that you have no data to return.
Now it depends if you have a project with clear requirements where you should always have a default value to return or some other data source if this one is not available, but if you just want the code to compile, you can have a simple return null; there.
If the return value is what concerns you, then you can return null or new Task<string>(() => string.Empty) since they basically mean that you have no data to return.
Now it depends if you have a project with clear requirements where you should always have a default value to return or some other data source if this one is not available, but if you just want the code to compile, you can have a simple return null; there.
answered Mar 22 at 14:08
meJustAndrewmeJustAndrew
3,24342552
3,24342552
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
add a comment |
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
What do you gain in returning null and swallowing the exception? 1. You'll have to add a null-check. 2. The caller cannot handle the exception. Lose-Lose-Situation :(
– Fildor
Mar 22 at 14:19
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
@Fildor I am not saying that he should be swallowing the exception, but depending on what he needs to achieve, he may want that (maybe with a logging mechanism). What I am doing is answering this: I guess I shouldn't be using throw, but the code want me to return something.
– meJustAndrew
Mar 22 at 14:27
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
Well, fair enough. But since the code does not compile anyway, I am suspicious this is not the actual problem.
– Fildor
Mar 22 at 14:33
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@meJustAndrew what if I'm returning a Task<List<Category>>? How should the exception return then?
– user10935587
Mar 22 at 14:57
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
@FredrikLinger depends on your requirements but you could return an empty list. Which only applies if it is not critical to make no distinction between a failed GET and "no elements".
– Fildor
Mar 22 at 15:05
add a comment |
Your code looks duplicated to me. Instead of making 3 different functions, you should rather have one with arguments:
public async Task<string> GetStringFromAPIAsync( string resource )
// check input
if( string.IsNullOrWhitespace(resource) ) throw new ArgumentException(nameof(resource));
using (HttpResponseMessage result = await _httpClient.GetAsync(resource))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
return await content.ReadAsStringAsync();
// Issue in your code: 'data' was out of scope for the return.
// string data = await content.ReadAsStringAsync();
// return data; <- "data" is not visible here!
Mind that I got rid of all the exception handling here, since from my POV, it should be done by the caller, which also gives you more flexibility.
For example: you could write another function for retry like so:
public async Task<string> GetStringFromAPIWithRetryAsync(string resource, int maxRetry)
// limit retry to 1 .. 100
for( int retry = Math.Min(Math.Max(1,maxRetry),100); retry > 0 ; retry--)
try
return await GetStringFromAPIAsync( resource );
catch(Exception ex) // Actually, you'd only catch exceptions where a retry makes sense.
if( retry > 0 )
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
else
throw;
If you just need a default in case of error, you could do this:
public async Task<string> GetStringFromAPIOrDefaultAsync(string resource, string defaultValue)
string returnValue = defaultValue;
try
returnValue = await GetStringFromAPIAsync( resource );
catch(Exception)
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
return returnValue;
}
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
add a comment |
Your code looks duplicated to me. Instead of making 3 different functions, you should rather have one with arguments:
public async Task<string> GetStringFromAPIAsync( string resource )
// check input
if( string.IsNullOrWhitespace(resource) ) throw new ArgumentException(nameof(resource));
using (HttpResponseMessage result = await _httpClient.GetAsync(resource))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
return await content.ReadAsStringAsync();
// Issue in your code: 'data' was out of scope for the return.
// string data = await content.ReadAsStringAsync();
// return data; <- "data" is not visible here!
Mind that I got rid of all the exception handling here, since from my POV, it should be done by the caller, which also gives you more flexibility.
For example: you could write another function for retry like so:
public async Task<string> GetStringFromAPIWithRetryAsync(string resource, int maxRetry)
// limit retry to 1 .. 100
for( int retry = Math.Min(Math.Max(1,maxRetry),100); retry > 0 ; retry--)
try
return await GetStringFromAPIAsync( resource );
catch(Exception ex) // Actually, you'd only catch exceptions where a retry makes sense.
if( retry > 0 )
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
else
throw;
If you just need a default in case of error, you could do this:
public async Task<string> GetStringFromAPIOrDefaultAsync(string resource, string defaultValue)
string returnValue = defaultValue;
try
returnValue = await GetStringFromAPIAsync( resource );
catch(Exception)
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
return returnValue;
}
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
add a comment |
Your code looks duplicated to me. Instead of making 3 different functions, you should rather have one with arguments:
public async Task<string> GetStringFromAPIAsync( string resource )
// check input
if( string.IsNullOrWhitespace(resource) ) throw new ArgumentException(nameof(resource));
using (HttpResponseMessage result = await _httpClient.GetAsync(resource))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
return await content.ReadAsStringAsync();
// Issue in your code: 'data' was out of scope for the return.
// string data = await content.ReadAsStringAsync();
// return data; <- "data" is not visible here!
Mind that I got rid of all the exception handling here, since from my POV, it should be done by the caller, which also gives you more flexibility.
For example: you could write another function for retry like so:
public async Task<string> GetStringFromAPIWithRetryAsync(string resource, int maxRetry)
// limit retry to 1 .. 100
for( int retry = Math.Min(Math.Max(1,maxRetry),100); retry > 0 ; retry--)
try
return await GetStringFromAPIAsync( resource );
catch(Exception ex) // Actually, you'd only catch exceptions where a retry makes sense.
if( retry > 0 )
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
else
throw;
If you just need a default in case of error, you could do this:
public async Task<string> GetStringFromAPIOrDefaultAsync(string resource, string defaultValue)
string returnValue = defaultValue;
try
returnValue = await GetStringFromAPIAsync( resource );
catch(Exception)
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
return returnValue;
}
Your code looks duplicated to me. Instead of making 3 different functions, you should rather have one with arguments:
public async Task<string> GetStringFromAPIAsync( string resource )
// check input
if( string.IsNullOrWhitespace(resource) ) throw new ArgumentException(nameof(resource));
using (HttpResponseMessage result = await _httpClient.GetAsync(resource))
using (HttpContent content = result.Content)
result.EnsureSuccessStatusCode();
return await content.ReadAsStringAsync();
// Issue in your code: 'data' was out of scope for the return.
// string data = await content.ReadAsStringAsync();
// return data; <- "data" is not visible here!
Mind that I got rid of all the exception handling here, since from my POV, it should be done by the caller, which also gives you more flexibility.
For example: you could write another function for retry like so:
public async Task<string> GetStringFromAPIWithRetryAsync(string resource, int maxRetry)
// limit retry to 1 .. 100
for( int retry = Math.Min(Math.Max(1,maxRetry),100); retry > 0 ; retry--)
try
return await GetStringFromAPIAsync( resource );
catch(Exception ex) // Actually, you'd only catch exceptions where a retry makes sense.
if( retry > 0 )
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
else
throw;
If you just need a default in case of error, you could do this:
public async Task<string> GetStringFromAPIOrDefaultAsync(string resource, string defaultValue)
string returnValue = defaultValue;
try
returnValue = await GetStringFromAPIAsync( resource );
catch(Exception)
Log.Warn("Attempt to get string from 0 failed! Reason: 1", resource, ex.Message);
return returnValue;
}
answered Mar 22 at 15:00
FildorFildor
7,22032348
7,22032348
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
add a comment |
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
in this case, where should I can the retry function ? Is there a way I can force a similar task exception to test? :)
– user10935587
Mar 25 at 8:53
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301295%2fhow-should-i-handle-exceptions-for-api-data-requester%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
There are several possibilities. Personally, I would not catch here. Just have it bubble up and handle retry in the caller.
– Fildor
Mar 22 at 14:04
That's not a question for us, but a (design) decision you have to make. When an exception occurs, you clearly have no string to return. So what do you want your code calling Dostuff* to do if there is no string to be returned?
– elgonzo
Mar 22 at 14:05
Does this even compile?
datashould be out of scope for return, since it is local to the "using" block.– Fildor
Mar 22 at 14:15
@Fildor I agree with what you are saying. I would like to retry if it should fail... Do you have any example how I can achieve this? And yeah, the string should be defined outside the using. My mistake.
– user10935587
Mar 25 at 8:39