Ignoring webservice errors. TryXXX pattern
I have a method that need to try to update my twitter status. I will send a lot of messages and I want to continue if some message throw a error.
Today I catch everything, but I dont like. Maybe should I put this catch at the caller? Or return exception instead bool?
public bool RefreshStatus(string status, out Status newStatus)
{
try
{
newStatu开发者_StackOverflow社区s = twitterContext.UpdateStatus(status);
return true;
}
catch
{
newStatus = null;
return false;
}
}
I call this method inside a for. I see method like Int32.TryParse and they dont do this, just ignore validations(I don´t have in this case)
What you can do is throw an Exception in RefreshStatus and catch that inside the loop.
By catching the Exception inside the loop you can batch-send the status updates and just accumulate the exceptions as they come in.
You could implement two versions of this method:
public bool TryRefreshStatus(string status, out Status new Status)
and
public Status RefreshStatus(string status)
The first could call the second within a try/catch block and return false if an exception is thrown. You should catch only the exceptions you expect to get thrown from the status update and not all exceptions (e.g. not System.Exception).
To solve the problem of pushing up lots of updates, I'd suggest creating a queue (first-in, first-out) that you add your updates to. Then, have a worker thread that attempts to post these updates to Twitter. When an update succeeds, you can remove it from the queue. Otherwise, you can keep trying.
You'd probably want to put some limit on the number of retries or the maximum age of a status update. Depending on how many you're posting, anything older than an hour (for example) might not be worth retrying as it may already be to far out of date.
Actually what TryParse do(at Int32, Single, etc) is not throw Exceptions, but not catch Exceptions thrown at called method.
What I really need is a twitterContext.TryUpdateStatus(status);
精彩评论