4

This question is more about the best practice for error handling within Angular 4.

After the reading the Angular 4 documentation I've found that all error handling should be done in the Services and the Components don't need to worry about that.

Currently I handle the error within the my subscribe call to my observable.

logIn(){

  this._userService.logIn({"email":this.loginForm.value.email,"password": this.loginForm.value.password})
  .subscribe(
  data => {//handle data here},

  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      // A client-side or network error occurred. Handle it accordingly.
      console.log('An error occurred:', err.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.log(`Backend returned code ${err.status}, body was: ${err.error.message}`);
    }
  }
)}

Im struggling to handle errors within Data Service. Im looking for some professional advice on how I can handle errors properly.

My Data Service:

logIn(body): Observable<any>{
return this._http.post('http://localhost:3000/api/login', body)
  .do(data => console.log('Login: ' + JSON.stringify(data)))
}

1 Answer 1

2

You can use catch and throw operator to preprocess the error (there is also finally operator btw):

logIn(body): Observable<any> {
    return this._http
        .post('http://localhost:3000/api/login', body)
        .do(data => console.log('Login: ' + JSON.stringify(data)))
        .catch(err => {
            // do whatever you want when error occurres
            console.log(err);

            // re-throw error so you can catch it when subscribing, fallback to generic error code
            return Observable.throw(err.message.toUpperCase() || 'API_ERROR');
        });
}

You will need to import those first to use them.

Sometimes it can be error that you want to ignore, then just return Observable.of(false); instead of the Observable.throw().

You should do this only for error pre-processing. You will still need to catch it later in the template (therefore we need to re-throw it), if you want to adjust the template based on it. But the code in component should ideally just catch the error and assign it to template (or show alert or whatever).

logIn() {
    this._userService.logIn({...})
        .subscribe(
            data => this.data = data,         // process data
            (err: string) => this.error = err // process error
        )
}
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.