http get error handling angular code example
Example 1: interceptor error handling angular 9
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
errorMsg = `Error: ${error.error.message}`;
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg);
})
)
}
}
Example 2: angular http error handling
import { Injectable } from '@angular/core';
import {
HttpInterceptor, HttpRequest,
HttpHandler, HttpEvent, HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor{
constructor() { }
handleError(error: HttpErrorResponse){
console.log("lalalalalalalala");
return throwError(error);
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>>{
return next.handle(req)
.pipe(
catchError(this.handleError)
)
};
}