1

How can I make this work?

switchMap((value: number) => throwError(value)
  .pipe(
    customeErrorHandler((value: number) => value * 3)
  );
);

export const customErrorHandler = (function: Function) =>
  catchError() => of( the function passed as parameter evaluated with the value );

Not passing the function and the value as separate arguments is the whole point.
For example with NgRx with an Effect you return:

map(() => new SuccessAction()),
catchError((value: number) => new FailureAction(value))

I want to do the same as that catchError, but using a custom handler.
Also, it must handle the error without affecting the success case, this is going to be passed inside the Effects pipe and the action returned will be different for success and failure.

f.e.:

type ActionCreationFunction = (payload: any) => Action;

export const effectsErrorHandler = (failureAction: ActionCreationFunction) =>
    catchError((err: any): Observable<Action> =>
      of(failureAction(payload))
         .pipe(tap(() => console.log(err))),

On an Effect:

.pipe(
  map(() => new AuthLoginSuccess()),
  effectsErrorHandler((counter: number) => new AuthLoginFailure(counter)),
);

Based on the link provided by @martin, this worked:

export const effectsErrorHandler = (failureAction: ActionCreationFunction) =>
    source =>
        Observable.create(subscriber =>
            source.subscribe(
                value => subscriber.next(value),
                err => subscriber.next(failureAction(err))
                    .pipe(tap(() => console.log(err))),
            ),
        );

But isn't there a way to just wrap the catchError like in my example instead of having to wrap everything like here?

3
  • So you want a custom operator github.com/ReactiveX/rxjs/blob/master/doc/operator-creation.md Commented Nov 4, 2018 at 18:35
  • With some differences, as the fact that I want to handle the error and not the normal case. I can't make it work, so can you make a working example? Because I had already seen that page and I can't make it work. Commented Nov 4, 2018 at 19:06
  • Link to documentation is outdated, I found this one useful rxjs.dev/guide/v6/… Commented Aug 6, 2020 at 8:32

1 Answer 1

3

This is what I was looking for:

export const effectsErrorHandler = (failureAction: ActionCreationFunction) =>
    (source: Observable) =>
        source
            .pipe(
                catchError(err =>
                    of(failureAction(err))
                        .pipe(tap(() => console.log(err))),
                ),
            );

Now I can extend it for my usecase

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.