Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle HTTP response codes in Angular 5+

Tags:

angular

Looking through the Angular 5+ guidance on making HTTP requests in Services we see the basic patterns appears as follows for a service:

getTasks(taskId: string): Observable<ITask[]> {
  var url = this.baseServiceUrl + 'task/' + taskId;

  this.fetchedTasks = this.http.get<ITask[]>(url);

  return this.fetchedTasks;
}

A component may use it as follows

getTasks(taskId: string): void {
  this.taskService.getTasks(taskId).subscribe(tasks => this.tasks = tasks);
}

Using the above case, how should this be modified to allow us to handle HTTP response codes such as 400, 403, 401, 404, and 5xx.

In short, we need the caller to be aware of faulted outcomes, vs, not found, etc. so they can handle related UI concerns

like image 829
JoeGeeky Avatar asked Jan 30 '18 21:01

JoeGeeky


3 Answers

The simplest way would be to just use the error object from observable. https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html

getTasks(taskId: string): void {
  this.taskService.getTasks(taskId).subscribe(data => {
        this.tasks = data;
    },
    err => {
        //handle errors here
    });
}

Your other options include overloading the default error handler in angular.

https://angular.io/api/core/ErrorHandler

like image 108
Calidus Avatar answered Sep 25 '22 11:09

Calidus


Your service can use catchError to return meaningful status/data back to the caller (component).

import { catchError } from 'rxjs/operators/catchError';
import { _throw } from 'rxjs/observable/throw';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';


getTasks(taskId: string): Observable<ITask[]> {
  var url = this.baseServiceUrl + 'task/' + taskId;

  this.fetchedTasks = this.http.get<ITask[]>(url)
        .pipe(catchError((res: HttpErrorResponse ) => {
                if (res.status === 400) {
                    var someErrorTheCodeNeedsToReturn = something;
                    return _throw(someErrorTheCodeNeedsToReturn);
                }
                return _throw(res.status); // unknown / unexpected error, just rethrow status or do something custom
            }));
  return this.fetchedTasks;
}
like image 31
Igor Avatar answered Sep 24 '22 11:09

Igor


I'm not entirely sure with observable, though I imagine it is a similar way. I do it like this:

public getAllInboxMessages(): Promise<Message[]> {
    return this.http.get<Message[]>(url)
        .toPromise()
        .catch(err => this.handleError(err));
}

  public handleError(error: any): Promise<never> {
    if (error.status === 401) {
      //
    } else if (error.status === 400) {
        //
      }
        return Promise.reject(error);
  }
like image 39
David Anthony Acosta Avatar answered Sep 23 '22 11:09

David Anthony Acosta