Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoiding throw AggregateException #217

Merged
merged 2 commits into from
Aug 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void ServiceUnavailableErrorWhenFailedToConn()
exception = Record.Exception(() => session.Run("RETURN 1"));
}
exception.Should().BeOfType<ServiceUnavailableException>();
exception.Message.Should().Be("Connection with the server breaks due to AggregateException: One or more errors occurred.");
exception.Message.Should().Contain("Connection with the server breaks due to IOException");
exception.GetBaseException().Should().BeOfType<SocketException>();
exception.GetBaseException().Message.Should().Contain("No connection could be made because the target machine actively refused it");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,13 @@ public void ShouldRetry()
}));
timer.Stop();

var error = e as AggregateException;
e.Should().BeOfType<ServiceUnavailableException>();
var error = e.InnerException as AggregateException;
var innerErrors = error.Flatten().InnerExceptions;
foreach (var innerError in innerErrors)
{
Output.WriteLine(innerError.Message);
innerError.Should().BeOfType<SessionExpiredException>();
}
innerErrors.Count.Should().BeGreaterOrEqualTo(5);
timer.Elapsed.TotalSeconds.Should().BeGreaterOrEqualTo(30);
Expand Down
2 changes: 1 addition & 1 deletion Neo4j.Driver/Neo4j.Driver.IntegrationTests/Examples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ public bool AddItem()
);
}
}
catch (AggregateException)
catch (ServiceUnavailableException)
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ public async Task<bool> AddItemAsync()
}
);
}
catch (AggregateException)
catch (ServiceUnavailableException)
{
return false;
}
Expand Down
3 changes: 2 additions & 1 deletion Neo4j.Driver/Neo4j.Driver.Tests/RetryLogicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ private void Retry(int index, IRetryLogic retryLogic)
}));
timer.Stop();

var error = e as AggregateException;
e.Should().BeOfType<ServiceUnavailableException>();
var error = e.InnerException as AggregateException;
var innerErrors = error.Flatten().InnerExceptions;

innerErrors.Count.Should().BeGreaterOrEqualTo(2);
Expand Down
20 changes: 14 additions & 6 deletions Neo4j.Driver/Neo4j.Driver/Internal/Connector/SocketConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,22 @@ internal SocketConnection(ISocketClient socketClient, IAuthToken authToken,

public void Init()
{
var connected = Task.Run(() => _client.StartAsync(_connectionTimeout)).Wait(_connectionTimeout);
if (!connected)
try
{
throw new IOException(
$"Failed to connect to the server {Server.Address} within connection timeout {_connectionTimeout.TotalMilliseconds}ms");
var connected = Task.Run(() => _client.StartAsync(_connectionTimeout)).Wait(_connectionTimeout);
if (!connected)
{
throw new IOException(
$"Failed to connect to the server {Server.Address} within connection timeout {_connectionTimeout.TotalMilliseconds}ms");
}

Init(_authToken);
}
catch (AggregateException e)
{
// To remove the wrapper around the inner exception because of Task.Wait()
throw e.InnerException;
}

Init(_authToken);
}

public async Task InitAsync()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
Expand Down Expand Up @@ -84,7 +85,7 @@ private async Task Connect(Uri uri, TimeSpan timeOut)
using (CancellationTokenSource cancellationSource = new CancellationTokenSource(timeOut))
{
var addresses = await uri.ResolveAsync(_ipv6Enabled).ConfigureAwait(false);
AggregateException innerErrors = null;
var innerErrors = new List<Exception>();
for (var i = 0; i < addresses.Length; i++)
{
try
Expand All @@ -101,13 +102,14 @@ private async Task Connect(Uri uri, TimeSpan timeOut)
catch (Exception e)
{
var error = new IOException($"Failed to connect to server '{uri}' via IP address '{addresses[i]}': {e.Message}", e);
innerErrors = innerErrors == null ? new AggregateException(error) : new AggregateException(innerErrors, error);
innerErrors.Add(error);

if (i == addresses.Length - 1)
{
// if all failed
throw new IOException(
$"Failed to connect to server '{uri}' via IP addresses'{addresses.ToContentString()}' at port '{uri.Port}'.", innerErrors);
$"Failed to connect to server '{uri}' via IP addresses'{addresses.ToContentString()}' at port '{uri.Port}'.",
new AggregateException(innerErrors));
}
}
}
Expand Down
21 changes: 15 additions & 6 deletions Neo4j.Driver/Neo4j.Driver/Internal/RetryLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,21 @@ public ExponentialBackoffRetryLogic(TimeSpan maxRetryTimeout, ILogger logger = n

public T Retry<T>(Func<T> runTxFunc)
{
AggregateException exception = null;
var exceptions = new List<Exception>();
var timer = new Stopwatch();
timer.Start();
var delayMs = _initialRetryDelayMs;
var counter = 0;
do
{
counter++;
try
{
return runTxFunc();
}
catch (Exception e) when (e.IsRetriableError())
{
exception = exception == null ? new AggregateException(e) : new AggregateException(exception, e);
exceptions.Add(e);

var delay = TimeSpan.FromMilliseconds(ComputeDelayWithJitter(delayMs));
_logger?.Info("Transaction failed and will be retried in " + delay + "ms.", e);
Expand All @@ -82,24 +84,28 @@ public T Retry<T>(Func<T> runTxFunc)
} while (timer.Elapsed.TotalMilliseconds < _maxRetryTimeMs);

timer.Stop();
throw exception;
throw new ServiceUnavailableException(
$"Failed after retried for {counter} times in {_maxRetryTimeMs} ms. " +
"Make sure that your database is online and retry again.", new AggregateException(exceptions));
}

public async Task<T> RetryAsync<T>(Func<Task<T>> runTxAsyncFunc)
{
AggregateException exception = null;
var exceptions = new List<Exception>();
var timer = new Stopwatch();
timer.Start();
var delayMs = _initialRetryDelayMs;
var counter = 0;
do
{
counter++;
try
{
return await runTxAsyncFunc().ConfigureAwait(false);
}
catch (Exception e) when (e.IsRetriableError())
{
exception = exception == null ? new AggregateException(e) : new AggregateException(exception, e);
exceptions.Add(e);

var delay = TimeSpan.FromMilliseconds(ComputeDelayWithJitter(delayMs));
_logger?.Info("Transaction failed and will be retried in " + delay + "ms.", e);
Expand All @@ -109,7 +115,10 @@ public async Task<T> RetryAsync<T>(Func<Task<T>> runTxAsyncFunc)
} while (timer.Elapsed.TotalMilliseconds < _maxRetryTimeMs);

timer.Stop();
throw exception;
throw new ServiceUnavailableException(
$"Failed after retried for {counter} times in {_maxRetryTimeMs} ms. " +
"Make sure that your database is online and retry again.", new AggregateException(exceptions));

}

private double ComputeDelayWithJitter(double delayMs)
Expand Down