Error handling not working in angular 6

I'm new in Angular and used this solution to generate entities and services according to my model.

One of the generated method is doing a post request to log my user and the request is well sent.

But when I get an error like Bad credentials from my API, the error is not handled and I get a runtime error on my angular app, and the console displays the error like this:

Http failure response for http://my-api.com/api/user/login: ErrorCode

Here's my code:

/**
     * Log a user by its credentials.
     */
    login(username : string, password : string) : Observable<NmUser> {
        let body = JSON.stringify({
            'username': username,
            'password': password
        });
        console.log(body);
        return this.http.post(this.userUrl + 'login', body, httpOptions)
            .pipe(
                map(response => new NmUser(response)),
                catchError(this.handleError)
            );
    }

// sample method from angular doc
    private handleError (error: HttpErrorResponse) {
        // TODO: seems we cannot use messageService from here...
        let errMsg = (error.message) ? error.message : 'Server error';
        console.error(errMsg);
        if (error.status === 401 ) {
            window.location.href = '/';
        }
        return Observable.throw(errMsg);
    }

What am I doing wrong ? Any help would be welcome.

Thanks !

Upvotes: 0

Views: 3524

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

errorHandler() method is throwing the error retrieved from backend.

This line

return Observable.throw(errMsg);

I guess you have not handled it properly in your Observable subscription. That is why it gets displayed on browser console

You may handle error in your component this way :

this.service.login(username, password)
    .subscribe(data => {},
               error => {                     
                   // redirect to some error component
         })

At some point in your code, you have to stop the Observable.throw chain, or else it gets displayed in the console.

Upvotes: 2

Related Questions