gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:36:41 24 4
gpt4 key购买 nike

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

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

非常感谢

最佳答案

有几种调试方法:

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

如果上述方法不起作用,您可以尝试使用此解决方案,我不久前也在互联网上通过使用 snackbar 找到了该解决方案组件,它将错误显示为弹出窗口:

错误.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;
}
}

全局错误处理程序组件.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 },
...

关于javascript - 如何获取 Angular 应用程序中的所有控制台错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58075967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com