在Angular应用程序中,我正在使用“材质”对话框来显示最终用户发生的所有错误消息。我构建了一个错误服务,该服务可以具有与服务器端(http)错误和客户端错误进行交互的方法。
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ErrorService {
getClientMessage(error: Error): string {
if (!navigator.onLine) {
return 'No Internet Connection';
}
return error.message ? error.message : error.toString();
}
getClientStack(error: Error): string {
return error.stack;
}
getServerMessage(error: HttpErrorResponse): string {
console.log(error.statusText);
return error.statusText;
}
getServerStack(error: HttpErrorResponse): string {
// handle stack trace
return 'stack';
}
}
我正在使用http拦截器来捕获http错误。
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
return throwError(error);
})
);
}
}
如您所见,我重试了一次端点命中,然后捕获任何错误。然后,我通过扩展Angular ErrorHandler的全局错误处理程序来运行所有错误。
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
HttpErrorResponse,
HttpHeaders,
HttpClient
} from '@angular/common/http';
import { PathLocationStrategy } from '@angular/common';
import { throwError, Observable } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
// Error handling is important and needs to be loaded first.
// Because of this we should manually inject the services with Injector.
constructor(
private injector: Injector,
public dialog: MatDialog,
private http: HttpClient
) {}
// Function to handle errors
handleError(error: Error | HttpErrorResponse) {
const errorService = this.injector.get(ErrorService);
const logger = this.injector.get(LoggerService);
console.log('error: ', error);
// Header options for http post
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
// Message variable to hold error message
let message;
// Variable to hold stacktrace
let stacktrace;
// Variable to hold url location of error
const url = location instanceof PathLocationStrategy ? location.path() : '';
if (error instanceof HttpErrorResponse) {
// Server error
message = errorService.getServerMessage(error);
stacktrace = errorService.getServerStack(error);
} else {
// Client Error
message = errorService.getClientMessage(error);
stacktrace = errorService.getClientStack(error);
}
// log errors
logger.logError(message, stacktrace);
console.log('message: ', message);
this.openDialog(message);
return throwError(error);
}
openDialog(data): void {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '60%',
data: data
});
dialogRef.afterClosed().subscribe((result) => {
// Redirect back to home (dashboard)?
console.log('in afterClosed: ' + result);
});
}
}
在这里我可以检查错误是服务器端还是客户端。然后,我找到了适当的错误服务方法。
问题 我真正遇到的问题是对话框。如您所见,我正在打开一个对话框并显示一个错误组件。该组件具有最终用户易于使用的视图。这是我的错误对话框组件。
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html'
})
export class ErrorDialogComponent implements OnInit {
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
private dialogRef: MatDialogRef<ErrorDialogComponent>
) {}
ngOnInit() {
console.log('data in oninit: ', this.data);
}
/**
* onCancelClick method
* Closes the Material Dialog
*
* @returns :void
*
*/
onCloseClick(): void {
console.log('data in onCloseClick: ', this.data);
this.dialogRef.close('Eureka!');
}
}
注意:我添加了oninit进行测试。它不在我的原始代码中。
我在视图中添加了两个按钮以测试错误逻辑...
// html
<button (click)="throwError()">Error</button>
<button (click)="throwHttpError()">HTTP</button>
// component
throwError() {
throw new Error('My Error');
}
throwHttpError() {
this.http.get('someUrl').subscribe();
}
当我单击客户端错误时,一切都会按设计进行。当我单击http错误按钮时,它将打开对话框,ngoninit中的console.log不会触发...,当我单击关闭按钮时,它将触发,但是afterClosed不会并且对话框也不会关闭。 / p>
所以我想知道问题可能是...区域?不能正确订阅可观察对象?
答案 0 :(得分:0)
我想出了解决方法...不确定确切的问题,但是能够使我的代码正常工作。这是我修改后的代码...
HttpErrorInterceptor
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
HttpHeaders
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
import { PathLocationStrategy } from '@angular/common';
import { ErrorService } from './error.service';
import { LoggerService } from './logger.service';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(
public dialog: MatDialog,
private errorService: ErrorService,
private logger: LoggerService
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
// Message variable to hold error message
let errorMessage = '';
// Variable to hold stacktrace
let stacktrace;
// Variable to hold url location of error
const url =
location instanceof PathLocationStrategy ? location.path() : '';
// Header options for http post
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
// server-side error
errorMessage = this.errorService.getServerMessage(error);
stacktrace = this.errorService.getServerStack(error);
// log errors
this.logger.logError(errorMessage, stacktrace);
if (typeof errorMessage !== 'undefined') {
this.openDialog(errorMessage);
} else {
this.openDialog('undefined');
}
return throwError(errorMessage);
})
);
}
openDialog(data): void {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '60%',
data: data
});
dialogRef.afterClosed().subscribe(result => {
// Redirect back to home (dashboard)?
console.log('in afterClosed http: ' + result);
});
}
}
GlobalErrorHandler
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
HttpErrorResponse,
HttpHeaders,
HttpClient
} from '@angular/common/http';
import { PathLocationStrategy } from '@angular/common';
import { throwError, Observable } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
// Error handling is important and needs to be loaded first.
// Because of this we should manually inject the services with Injector.
constructor(
private injector: Injector,
public dialog: MatDialog,
private http: HttpClient
) {}
// Function to handle errors
handleError(error: Error) {
const errorService = this.injector.get(ErrorService);
const logger = this.injector.get(LoggerService);
// Header options for http post
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
// Message variable to hold error message
let errorMessage;
// Variable to hold stacktrace
let stacktrace;
// Variable to hold url location of error
const url = location instanceof PathLocationStrategy ? location.path() : '';
if (error instanceof Error) {
// Client Error
errorMessage = errorService.getClientMessage(error);
stacktrace = errorService.getClientStack(error);
this.openDialog(errorMessage);
}
// log errors
logger.logError(errorMessage, stacktrace);
return throwError(error);
}
openDialog(data): void {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '60%',
data: data
});
dialogRef.afterClosed().subscribe(result => {
// Redirect back to home (dashboard)?
console.log('in afterClosed error: ' + result);
});
}
}
其他所有内容均保持不变。