How to handle RxJs timeout complete - Angular HttpClient
Asked Answered
N

2

12

How to detect an error by timeout operator? I would like to show an alert or something like that just when the server doesn't response.

I have a similiar code in my interceptor:

this.http.post('http://localhost:3000/api/core', data)
        .pipe(
            timeout(30000),
            map((response: any) => { // Success...
              return response;
            }),
            catchError((error) => { // Error...
              // Timeout over also handled here
              // I want to return an error for timeout
              return throwError(error || 'Timeout Exception');
            }),
            finalize(() => {
              console.log('Request it is over');
            })
        );

["rxjs": "^6.0.0", "@angular/http": "^6.0.3",]

Nephogram answered 10/11, 2018 at 1:49 Comment(1)
It will throw a TimeoutError which you can look for using instanceof.Dealate
N
21

This works

import { throwError, TimeoutError } from 'rxjs';

catchError((error) => { // Error...
   // Handle 'timeout over' error
   if (error instanceof TimeoutError) {
      return throwError('Timeout Exception');
   }

   // Return other errors
   return throwError(error);
})

I implemented this at my intecerptor that has other functionalities, the code here

Nephogram answered 30/11, 2018 at 19:3 Comment(4)
The page was not found. Could you upload it again?Repay
Hey. This works for me but I still get the error ERROR Error: Uncaught (in promise): TimeoutError: Timeout has occurredDeface
If you don't want to return a error (you shoud) innstead of "throwError" return "of". And you will can handle in your map, or tap operatorNephogram
I was returning err instead of caught. Now it's working. Thank youDeface
F
-4

You can use timeoutWith operator to achieve this.

return this.http.post('http://localhost:3000/api/core', data).pipe(
      timeoutWith(3000, observableThrowError(new Error('Http Timeout exceeds'))),
      map((response: any) => { // Success...
              return response;
      }),
      catchError((error: HttpErrorResponse) => this.handleError(error))
    );
Finnish answered 10/11, 2018 at 7:0 Comment(1)
observableThrowError?Casar

© 2022 - 2024 — McMap. All rights reserved.