gpt4 book ai didi

angular - 自定义错误处理程序抛出错误 : Cannot read property 'get' of undefined ( Injector )

转载 作者:太空狗 更新时间:2023-10-29 17:39:03 26 4
gpt4 key购买 nike

我正在 Angular 4 中构建一个自定义错误处理程序,以使用错误拦截器处理不同类型的应用程序错误

创建一个基类 ( app-error.ts ) 和其他类(例如,为了处理 403 错误创建类 access-denied.ts )扩展这个基类。

在基类中注入(inject)了一个服务toastrService,我想显示来自子类的自定义消息,但它给出了错误

无法读取未定义的属性“get”

此问题与 OOPS 概念有关。我不明白如何覆盖父方法或使用我的自定义参数调用。

TS 版本 2.3.3 Angular v 4.3.4

应用程序模块.ts

providers: [
{ provide: ErrorHandler, useClass: AppErrorHandler }
]

注意:AppErrorHandler 类与 AppError 完全不同,AppError 扩展了处理系统错误的 Angular ErorHandler 接口(interface)。

错误拦截器

import { Router } from '@angular/router';
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpResponse, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

import {
AuthFail,
BadInput,
NotFoundError,
ServerError,
AppError,
AccessDenied,
} from '../shared/errors';
import { AuthenticationService } from './../authentication/authentication.service';


@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

private auth: AuthenticationService;
constructor(private router: Router, private injector: Injector) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthenticationService);
return next.handle(req).catch((err: HttpErrorResponse) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
return Observable.throw(new AuthFail(err.error));
}
if (err.status === 400) {
return Observable.throw(new BadInput(err.error));
}
if (err.status === 404) {
return Observable.throw(new NotFoundError());
}
if (err.status === 403) {
return Observable.throw(new AccessDenied());
}
return Observable.throw(new AppError(err));
}
});
}
}

拒绝访问.ts

import { AppError } from './app-error';
export class AccessDenied extends AppError {
constructor(public originalError?: any) {
super();
console.log('inside acces denied constructor');
// super.handleError("superrrrr"); // this also doesn't work
}

public handleError(): void {
console.log('handleError: ', );
super.handleError("Access denined error occured");
}
}

应用程序错误.ts

import { Inject, Injector } from "@angular/core";

import { ToastrService } from "ngx-toastr";

export class AppError {
toastrService: ToastrService;
constructor(public originalError?: any, private injector?: Injector) {
this.toastrService = this.injector.get(ToastrService);
}

// NOTE: using getter seems impossible to access in child so add the same in constructor
// get toastrService(): ToastrService {
// return this.injector.get(ToastrService);
// }

public handleError(msg: string): void {
this.toastrService.error(`Error Message: ${msg}`,
"Error", {
closeButton: true,
timeOut: 5000,
onActivateTick: true
}
);
}

}

给出错误


core.es5.js:1020 ERROR TypeError: Cannot read property 'get' of undefined 
at AccessDenied.AppError (app-error.ts:8)
at new AccessDenied (access-denied.ts:6)
at CatchSubscriber.eval [as selector] (error.interceptor.ts:61)
at CatchSubscriber.error (catchError.js:105)
at XMLHttpRequest.onLoad (http.es5.js:1739)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at ZoneTask.invokeTask [as invoke] (zone.js:496)

最佳答案

AccessDenied 错误地扩展了 AppErrorsuper() 导致 injector 未定义,并且 injectorAppError 构造函数中不应该是可选的,因为它是必需的。

可以通过强制设置参数来解决这个问题:

constructor(private injector: Injector, public originalError?: any) {
this.toastrService = this.injector.get(ToastrService);
}

AccessDenied中可以省略构造函数。并且应该像 new AccessDenied(injector) 一样被实例化。

这里真正的问题是 AppError 做了它不应该做的工作。考虑到它只包含稍后可以用 err instanceof AppError 确定的错误,它不应该产生目前在 handleError 中产生的副作用。

handleError 中的逻辑可以移至 ToastrService 中的方法或接受 AppError 实例的单独错误服务。如果需要为错误类型提供默认消息,例如 发生拒绝访问错误AppError 可以具有包含该消息的公共(public)属性。

关于angular - 自定义错误处理程序抛出错误 : Cannot read property 'get' of undefined ( Injector ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49148781/

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