Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - how to simulate HttpError response in service

How can I simulate HTTP error response in Angular service? I often need to handle different HTTP error codes and sometimes I need implement solution, but backend is not ready. How can I mock errors from backend? Example code

  public getData(): Observable<Response> {
    return this.httpClient.get<Response>(`${this.endpoint}`);
  }
like image 266
Kamil Naja Avatar asked Aug 20 '20 19:08

Kamil Naja


1 Answers

Simplest solution - you can create an HttpErrorResponse instance, set error status and then return this object as service fake response.

  public getData(): Observable<Response> {
    const error = new HttpErrorResponse({ status: 422 });
    return of(error) as any;
  }

or 
  public getData(): Observable<Response> {
    const error = new HttpErrorResponse({ status: 422 });
    return throwError(error) as any;
  }
like image 183
Kamil Naja Avatar answered Oct 18 '22 01:10

Kamil Naja