14

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

1 Answer 1

29

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;
  }
3
  • 1
    Why you posted question then? Aug 20, 2020 at 19:40
  • 14
    Because I want share my knowledge, this is popular question. stackoverflow.blog/2011/07/01/…
    – Kamil Naja
    Aug 20, 2020 at 19:48
  • 1
    For rxjs 7.8 or greater you'll want to use the factory syntax throwError(() => error);
    – swandog
    Apr 14 at 12:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.