如何处理Angular 8中的控制台(http)错误?

如何处理Angular 8中的控制台(http)错误?,angular,error-handling,angular-http-interceptors,Angular,Error Handling,Angular Http Interceptors,我想处理控制台上记录的错误。基本上,我想把它们藏起来。 使用拦截器来处理错误。 以下是该项目的代码段: 组成部分: //app.component.ts getUsersData() { this.userService.getUsers().subscribe( res => { this.data = res; } ) } 模块:(在模块提供程序中提供HttpInterceptor) Http拦截器: //http-erro

我想处理控制台上记录的错误。基本上,我想把它们藏起来。 使用拦截器来处理错误。 以下是该项目的代码段:

组成部分:

//app.component.ts
getUsersData() {
    this.userService.getUsers().subscribe(
      res => {
        this.data = res;
      }
    )
  }
模块:(在模块提供程序中提供HttpInterceptor)

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);
          })
        )
    }
  }
//http-error.interceptor.ts
进口{
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
}来自“@angular/common/http”;
从“rxjs”导入{observatable,throwerr};
从“rxjs/operators”导入{retry,catchError};
导出类HttpErrorInterceptor实现HttpInterceptor{
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
返回next.handle(请求)
.烟斗(
重试(1),
catchError((错误:HttpErrorResponse)=>{
让errorMessage='';
if(error.error instanceof ErrorEvent){
//客户端错误
errorMessage=`Error:${Error.Error.message}`;
}否则{
//服务器端错误
errorMessage=`错误代码:${Error.status}\n消息:${Error.message}`;
}
窗口警报(错误消息);
返回投掷器(错误消息);
})
)
}
}
您可以试试这个吗

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

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

if (window) {
   window.console.log = function () { };
}
注意:这将停止执行中的任何内容,请确保在开发模式下对此进行注释

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