Angular - how to simulate HttpError response in service
Asked Answered
C

1

15

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}`);
  }
Carnatic answered 20/8, 2020 at 19:37 Comment(0)
C
33

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;
  }
Carnatic answered 20/8, 2020 at 19:37 Comment(3)
Why you posted question then?Odelia
Because I want share my knowledge, this is popular question. stackoverflow.blog/2011/07/01/…Carnatic
For rxjs 7.8 or greater you'll want to use the factory syntax throwError(() => error);Coastline

© 2022 - 2024 — McMap. All rights reserved.