JoeGeeky
JoeGeeky

Reputation: 3796

How to handle HTTP response codes in Angular 5+

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

Upvotes: 5

Views: 15938

Answers (3)

David Anthony Acosta
David Anthony Acosta

Reputation: 4908

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);
  }

Upvotes: 3

Igor
Igor

Reputation: 62228

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;
}

Upvotes: 3

Calidus
Calidus

Reputation: 1414

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

Upvotes: 3

Related Questions