简体   繁体   中英

How to handle console (http) errors in Angular 8?

I want to handle errors logged on the console. basically I want to hide them from the console. Used interceptor to handle errors. Following is the snippet for same:

Component:

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

Module: (provided HttpInterceptor in the module provider)

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

Http Interceptor:

//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);
          })
        )
    }
  }

Might you try this?

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

I am hoping all you want is to hide the console data. In that case, you can overwrite the window.console.log function. In your main.ts file,

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

Note: This will stop consoling anything in execution, make sure you comment this out in dev mode

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.

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