I have a data.json file as below.
[
{"value":1},
{"value":2},
{"value":3},
{"value":3}
]
& I am using Http to get the data. Data is coming properly but what if my server is turned off, then it throws error i want to show some custom message to user instead of that error. Below is my function which fetches the data.
data: any;
getData() {
this.http.get('http://localhost/php/data.json').subscribe((res) => {
this.data = res;
console.log(this.data);
})
}
ngOnInit() {
this.getData();
}
getData() {
this.http.get('http://localhost/php/data.json').subscribe((res) => {
this.data = res;
console.log(this.data);
},(err:HttpErrorResponse)=>{handle your error here});
subscribe accepts error handling callback as 2nd argument. You can check API details here
You can also use the catchError opertor provided by the rxjs
import {catchError} from 'rxjs/operators'
this.http.get('http://localhost/php/data.json')
.pipe (
catchError((error) => // handle the error here; )
)
.subscribe((res) => {
this.data = res;
console.log(this.data);
})
if you want to capture a specific instance than :
getData() {
this.http.get('http://localhost/php/data.json').subscribe((res) => {
this.data = res;
console.log(this.data);
}, (err:HttpErrorResponse) => {
consdole.log(err)
})
}
I will suggest you to use
intercepter
for centralise theerror
handling:
http-intercepter.ts:
import { Injectable, Injector } from '@angular/core';
import {
HttpEvent,
HttpHeaders,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private appService: AppService) {
}
/**
*
* @param req - parameter to handle http request
* @param next - parameter for http handler
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
/**
* Handle newly created request with updated header (if given)
*/
return next.handle(req).do((event: HttpEvent<any>) => {
/**
* Sucessfull Http Response Time.
*/
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
}
}, (err: any) => {
/**
* redirect to the error_handler route according to error status or error_code
* or show a modal
*/
if (err instanceof HttpErrorResponse) {
console.log(err);
}
});
}
}
in module.ts:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true,
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.