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)); }
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'); } });
Top comments (0)