Skip to content

Unobserved task exception when attempting to connect to not existing server #998

@DieterSedlmayer

Description

@DieterSedlmayer

Observed behavior

In below console app an Unobserved task exception is observed although the connect attempt is in a try/catch block.

Expected behavior

All exceptions can be handled gracefully.

Server and client version

Version 2.6.11

Host environment

No response

Steps to reproduce

using NATS.Client.Core;

TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
{
    Console.WriteLine($"Unobserved task exception: {eventArgs.Exception}");
    eventArgs.SetObserved();
};

var connection
    = new NatsConnection(
        NatsOpts.Default with { Url = "nats:/user@pass:sorry" });

await using (connection.ConfigureAwait(false))
{
    try
    {
        await connection.ConnectAsync().ConfigureAwait(false);
        Console.WriteLine("Connected to NATS server.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to connect to NATS server: {ex.Message}");
    }

    await Task.Delay(500).ConfigureAwait(false);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine("Exiting application.");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions