简体   繁体   English

HTTP响应错误处理Angular应用程序

[英]HTTP Response Error Handling Angular Application

I have a data.json file as below. 我有一个data.json文件,如下所示。

[
    {"value":1},
    {"value":2},
    {"value":3},
    {"value":3}
]

& I am using Http to get the data. &我正在使用Http获取数据。 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 您可以在此处查看API详细信息

https://angular.io/api/common/http/HttpErrorResponse https://angular.io/api/common/http/HttpErrorResponse

You can also use the catchError opertor provided by the rxjs 您还可以使用rxjs提供的catchError运算符

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 the error handling: 我建议您使用intercepter集中处理error

http-intercepter.ts: 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: 在module.ts中:

providers: [ 提供者:[

{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true,
}
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM