Last active
March 28, 2019 11:28
-
-
Save nicowernli/f36651c2b38a0ea0e477e0cba1f65b31 to your computer and use it in GitHub Desktop.
An error interceptor to manage all HTTP errors in a single way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from '@angular/core'; | |
import {HttpHandler, HttpRequest, HttpInterceptor} from '@angular/common/http'; | |
import {throwError} from 'rxjs'; | |
import {catchError} from 'rxjs/internal/operators'; | |
import {ErrorService} from '../my-services/error.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class HttpErrorInterceptor implements HttpInterceptor { | |
construct(private errorService: ErrorService) {} | |
intercept(req: HttpRequest<any>, next: HttpHandler) { | |
return next.handle(req).pipe( | |
catchError(error => { | |
let errorMessage = ''; | |
if (error instanceof ErrorEvent) { | |
// client-side error | |
errorMessage = `Client-side error: ${error.error.message}`; | |
} else { | |
// backend error | |
errorMessage = `Server-side error: ${error.status} ${error.message}`; | |
} | |
// aquí podrías agregar código que muestre el error en alguna parte fija de la pantalla. | |
this.errorService.show(errorMessage); | |
return throwError(errorMessage); | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment