Why does SignalR recommend using finally to propagate errors in streams?

Viewed 43

The SignalR docs on streaming state:

Wrap logic in a try ... catch statement. Complete the Channel in a finally block. If you want to flow an error, capture it inside the catch block and write it in the finally block.

They then proceed to give an example that goes through these convolutions for no apparent gain. Why is this? What difference does it make whether one captures an exception and completes the channel from the finally block versus completing then and there in the catch block?

1 Answers

Possibly to centralize the writer completion logic, even if takes just a single invocation - and you may want to insert additional related logic there (such as logging), if needed.

Exception localException = null;

try
{
    // ...
}
catch (Exception ex)
{
    localException = ex;
}
finally
{
    writer.Complete(localException);
}

versus:

var completed = false;

try
{
    // ...
}
catch (Exception ex)
{
    writer.Complete(ex);
    completed = true;
}
finally
{
    if (!completed)
    {
        writer.Complete(null);
    }
}
Related