DEV Community

Matheus Gonçalves Murta
Matheus Gonçalves Murta

Posted on

Angular Mock HttpErrorResponse Example

Easy way to create Mock HttpErrorResponse with Angular

Insert into your Service

import { HttpErrorResponse } from '@angular/common/http';

  public simulateForbiddenError(): Observable<any> {
    return throwError(new HttpErrorResponse({ status: 403 })).pipe(delay(3000));
  }

  public simulateBadRequestError(): Observable<any> {
    return throwError(new HttpErrorResponse({ status: 400 })).pipe(delay(3000));
  }

  public simulateGatewayTimeoutError(): Observable<any> {
    return throwError(new HttpErrorResponse({ status: 504 })).pipe(delay(3000));
  }

Enter fullscreen mode Exit fullscreen mode

Use

this.myService.simulateForbiddenError().subscribe({
 next: (data) => {
    // Handle the data
    console.log(data);
 },
 error: (error) => {
    // Handle the error
    console.error(error);
 },
 complete: () => {
    // Handle completion
    console.log('Observable completed');
 }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)