http interceptor service error angular 9 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: angularjs interceptor
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
return config;
},
'requestError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
},
'response': function(response) {
}
};
});