Search code examples
angularobservablethrow

Angular 4: How to properly handle app level http error as Observable error?


I use an HTTP API that returns app-level error thru a json where status == 'error'.

In my signUp service, I do that:

    return this.userService
        .create(user)
        .map(
            json => { 
                console.log(json);
                if (json.status=='error') {
                    console.log('error return throw');
                    return Observable.throw('Credentials mismatch or not existing');
                }

                const user = json.data as User;    
                return user;
            },
            err => { 
                console.log(err);
            }
        );

And in my singUp.component, I do that:

    onSubmit() {
        // blahblah

        this.si
        .signUp(this.credentials.emailAddress, this.credentials.password, this.credentials.zipCode)
        .subscribe(
        user => {
            console.log(user);
            console.log(`SignUpComponent.onSubmit() found user.userId ${user.userId}`);
            this.router.navigate(['signin']);
        },
        err => {
            this.errorMessage = `*** SignUpComponent: Error while signing up {err}`;
            console.error('*** SignUpComponent: Error while signing up', err);
            this.resume();
            //this.router.navigate(['signup']);
        });

        this.ngOnChanges();
    }

Unfortunately, when the service returns an error (with the Observable.throw()), the component doesn't trigger the err closure but the user closure passing the Observable.throw as the user parameter.

I wish I had the err closure to be triggered.

What Im missing there?

Update: Here is what I get:

[Log] SigninService.signUp, zipCode=
[Log] {data: null, status: "error", message: "Error user create: - missing id   API usage v1b3: Tu…ate\"}↵post: []↵.↵", ws: "v1b3: Tuesday, August 25th 2017 20h20 @ Tanger"}
[Log] error return throw
[Log] ErrorObservable {_isScalar: false, error: "Credentials mismatch or not existing", scheduler: undefined, _subscribe: function, …}
[Log] SignUpComponent.onSubmit() found user.userId undefined

Solution

  • You are handling the exception inside the user call back, it means it was succesfuly executed, in that case Observable.throws won't really act as an exception. In order to achieve that, you must use throw new Error("Credentials mismatch or not existing") that must replace return Observable.throw("Credentials mismatch or not existing"); Please, look at this: How to throw error from RxJS map operator (angular)