如何在 Angular 应用程序中获取所有控制台错误消息

How to get all console error messages in Angular application

我正在开发一个 angular 应用程序,问题是当我想在一些智能电视上调试它时没有调试模式,并且在后台我有一些错误导致应用程序崩溃,那么,有什么方法可以获取所有错误消息并将其打印在我的应用程序页面的一部分中吗?

其实我想在我自己的应用程序中有某种虚拟控制台。

非常感谢

有几种调试方法:

  • Console.log() - 这会将您的消息输出到控制台。不过不确定你是否可以在电视上看到它。
  • 创建全局错误处理程序,如 Angular documentation
  • 中所提供

如果上述方法不起作用,您可以尝试使用这个解决方案,我前段时间也在互联网上的某个地方找到了这个解决方案,方法是使用 snackbar 组件,该组件将错误显示为弹出窗口:

error.service.ts:

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class ErrorService {

    checkOnline()
    {
        if (!navigator.onLine) {
            return 'No Internet Connection';
        }
    }

    getClientMessage(error: Error): string {
        return error.message ? error.message : error.toString();
    }

    getClientStack(error: Error): string {
        return error.stack;
    }

    getServerMessage(error: HttpErrorResponse): string {
        var msg = error.error.Message;
        if (!!msg)
            return msg + " : " + error.error.ExceptionMessage;
        return "Application can not execute because API hasn\'t been started";
    }

    getServerStack(error: HttpErrorResponse): string {
        return error.error.StackTrace;
    }
}

全局错误处理程序-component.ts:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorService } from './services/error.service';
import { MatSnackBar } from '@angular/material';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler
{
    constructor(private injector: Injector, public snackBar: MatSnackBar) { }

    handleError(error: Error | HttpErrorResponse)
    {
        const errorService = this.injector.get(ErrorService);
        let message;
        let stackTrace = errorService.getClientStack(error);

        if (error instanceof HttpErrorResponse) // Server Error
            message = errorService.getServerMessage(error);
        else // Client Error
            message = errorService.getClientMessage(error);

        this.snackBar.open(message, 'X', { panelClass: ['error'] });
    }
}

app.module.ts:

import { GlobalErrorHandler } from './global-error-handler.component';
import { MatSnackBarModule } from '@angular/material/snack-bar';
...
  imports: [
...
    MatSnackBarModule,
...
  ],
  providers: [
...
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
...

你可以覆盖 console.error 方法并创建像间谍一样的平滑

@Injectable({
    providedIn:'root'
})
export class ConsoleSpyService {
  private errorStack :any[] = []
  constructor() { 
    const errMethod = console.error;

    console.error= (...args) => { 
      this.errorStack.push(args);

      errMethod(``,...args)
    }

    Object.freeze(console)
  }


  get errorList() {
    return this.errorStack;//.slice(0);
  }
}

你需要注入这个 class 所以它创建了

export class AppModule {

  constructor(c:ConsoleSpyService){}

 }

在组件中注入服务

  constructor(private conSpyServ:ConsoleSpyService) {

  }

  get errors(){
    return this.conSpyServ.errorList;
  }

模板(显示错误列表)

<div class="errors" *ngFor="let error of errors">
  {{error.join(' ')}}
</div>

you can display logging to console browser by comment this line errMethod(,...args) in ConsoleSpyService class

demo