【发布时间】:2019-07-04 21:07:45
【问题描述】:
在https://angular.io/api/core/ErrorHandler 之后,我可以覆盖全局错误处理程序来处理错误对象,并且我喜欢我可以声明自己的全局错误处理程序并将其导入任何我需要的地方的方式。
但是对于 RxJS,我经常使用 catchError(this.handleError(my, params, go, here))。
我想将我的handleError() 方法全球化,并将其合并到我的全局错误处理程序中。但这看起来在技术上是不可能的。
这就是我的 handleError 方法所做的,它结合 RxJS 的 catchError 通过 (1) 将其记录到记录器 (2) 将其记录到控制台和 (3) 返回一个虚拟的 @987654326 来处理错误@让RxJS调用能够顺利完成。
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private messageService: MessageService) { }
public handleError<T>(
error: HttpErrorResponse, operation = 'operation', result?: T) {
var errorMessage = '';
if (error.error instanceof ProgressEvent) {
errorMessage = `Client error occurred: ${error.message}`;
} else {
errorMessage = `Adam's error ${error.status}: ${error.message}`;
}
console.error(errorMessage);
this.messageService.add(`${operation} failed: ${errorMessage}`);
return of(result as T);
}
}
作为全局错误处理程序,我怎样才能做到这一点?还是我应该采取不同的方法?我知道我可以创建一个 “错误服务” 来保存我的通用 handleError(),并像其他所有服务一样将其注入到任何地方,但这似乎很笨重。
【问题讨论】:
标签: angular typescript error-handling rxjs