Search code examples
asynchronouserror-handlingmergerxjsbehaviorsubject

How do I throw an error asynchronously in RxJs?


I have an observer that tracks questions and answers of a command line interface. What I would like to do is inject an error into the observer given a certain event in my code in order to terminate the observer and its subscription downstream. It is unknown at what time it runs.

I've tried throwing errors from a merge of a subject and the observable but I cannot seem to get anything out of it.

Here is the relevant code:

        this.errorInjector$ = new Subject<[discord.Message, MessageWrapper.Response]>();
        ....
        this.nextQa$ = merge(
            nextQa$,
            this.errorInjector$.pipe(
                tap((): void => {
                    throw (new Error('Stop Conversation called'));
                }),
            ),
        );

        // start conversation
        Utils.logger.trace(`Starting a new conversation id '${this.uuid}' with '${this.opMessage.author.username}'`);
    }

    getNextQa$(): Observable<[discord.Message, MessageWrapper.Response]> {
        return this.nextQa$;
    }

    stopConversation(): void {
        this.errorInjector$.next(
            null as any
        );
    }

The this.nextQa$ is merged with the local nextQa$ and the errorInjector$. I can confirm that stop conversation is being called and downstream is receiving this.nextQa$ but I am not seeing any error propagate downstream when I try to inject the error. I have also tried the this.errorInjector.error() method and the map() operator instead of tap(). For whatever reason I cannot get the two streams to merge and to throw my error. To note: this.nextQa$ does propagate errors downstream.

I feel like I am missing something about how merge or subjects work so any help or explanation would be appreciated.

EDIT

Well I just figured out I need a BehaviorSubject instead of a regular subject. I guess my question now is why do I need a BehaviorSubject instead of a regular Subject just to throw an error?

EDIT 2

BehaviorSubject ALWAYS throws this error which is not what I want. It's due to the nature of its initial emission but I still don't understand why I can't do anything with a regular subject in this code.


Solution

  • The problem is getting the object with the stopConversation(): void from the dictionary object I have. The this object is defined and shows errorInjector$ is defined but the debugger tells me that errorInjector$ has become undefined when I hover over the value. At least that's the problem and I'll probably need to ask another question on that.