【问题标题】:How to handle console (http) errors in Angular 8?如何处理 Angular 8 中的控制台(http)错误?
【发布时间】:2020-05-22 16:46:43
【问题描述】:

我想处理控制台上记录的错误。基本上我想从控制台隐藏它们。 使用拦截器来处理错误。 以下是相同的 sn-p:

组件:

//app.component.ts
getUsersData() {
    this.userService.getUsers().subscribe(
      res => {
        this.data = res;
      }
    )
  }

Module:(在module provider中提供了HttpInterceptor)

//app.module.ts
 providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true
    }
  ],

Http 拦截器:

//http-error.interceptor.ts
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpResponse,
    HttpErrorResponse
  } from '@angular/common/http';
  import { Observable, throwError } from 'rxjs';
  import { retry, catchError } from 'rxjs/operators';

  export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(request)
        .pipe(
          retry(1),
          catchError((error: HttpErrorResponse) => {
            let errorMessage = '';
            if (error.error instanceof ErrorEvent) {
              // client-side error
              errorMessage = `Error: ${error.error.message}`;
            } else {
              // server-side error
              errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
            }
            window.alert(errorMessage);
            return throwError(errorMessage);
          })
        )
    }
  }

【问题讨论】:

    标签: angular error-handling angular-http-interceptors


    【解决方案1】:

    你可以试试这个吗?

    subscribe(
       (response) => {
          this.repos = response;
       },
       (error) => {
          //Handle the error here
          //If not handled, then throw it
          throw error; 
       }
    

    【讨论】:

      【解决方案2】:

      我希望你想要的只是隐藏控制台数据。 在这种情况下,您可以覆盖window.console.log 函数。 在您的 ma​​in.ts 文件中,

      if (window) {
         window.console.log = function () { };
      }
      

      注意:这将停止安慰正在执行的任何内容,请确保您在开发模式下将其注释掉

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-06
        • 2018-11-30
        • 1970-01-01
        • 2012-11-16
        • 2016-07-12
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多