Skip to content

Exception swallowed if thrown from OnNext invoked by Subscribe  #1904

@seanreid1201

Description

@seanreid1201

Bug

Which library version?

System.Reactive version 5.0.0

What are the platform(s), environment(s) and related component version(s)?

Windows 10, .NET 6, Visual Studio 2022

What is the use case or problem?

We have a large codebase which was originally full of observable-like things. In the process of converting these to be observables, we came across a scenario where an exception was thrown which should have propagated out as nobody caught it, but instead it was suppressed silently by the Rx library.
I've reduced the problem to a minimal example below.

What is the expected outcome?

An exception which is thrown should not be caught and suppressed by Rx.

What is the actual outcome?

The exception is suppressed.

Do you have a code snippet or project that reproduces the problem?

Here's a unit test which should fail but instead passes:

public class ObservableTests
{
    private class SingleValueSubject : IObservable<int>
    {
        public IDisposable Subscribe(IObserver<int> observer) =>
            Observable.Return(1).Subscribe(observer);
    }
    
    [Fact]
    public void ThrownExceptions_ShouldPropagateOut()
    {
        using var source = new BehaviorSubject<int>(1);
        var wrapped = new SingleValueSubject();
        
        var threw = false;

        source.Subscribe(
            _ => wrapped.AsObservable().Subscribe(
                _ =>
                {
                    threw = true;
                    throw new Exception();
                }));

        // If `threw` is true, then an exception was thrown but not caught, so the test should fail.
        // If threw is false, then this assertion should fail.
        // So how can the test pass?
        Assert.True(threw);
    }
}

I've tried searching for this but haven't come across anything.
If this is intended behaviour, is there a rule we should follow to avoid this happening in our codebase in future?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions