gpt4 book ai didi

javascript - Angular 2 - 全局错误处理程序仅在未捕获错误时执行

转载 作者:行者123 更新时间:2023-11-30 20:07:34 24 4
gpt4 key购买 nike

在我的 Angular 应用程序中,有一个全局错误处理程序和一个负责生成 http 的服务。调用,返回类型为 Observable<any> .有些服务已明确处理错误,有些则没有。

对于那些没有被捕获的,全局错误(具有类“CustomErrorHandler”)运行正常。对于已被妥善处理和捕获的服务调用,全局错误似乎并未触发。

My question: Is there a way to execute the global error handling irrespective of whether the http service calls has been handled or not?

自定义错误处理程序.service.ts

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }

handleError(error) {
error = error || new Error('There was an unexpected error');
const loggingService: LoggerService = this.injector.get(LoggerService);
const location = this.injector.get(LocationStrategy);
const message = error.message ? error.message : error.toString();
const url = location instanceof PathLocationStrategy
? location.path() : '';

// get the stack trace, lets grab the last 10 stacks only
StackTrace.fromError(error).then(stackframes => {
const stackString = stackframes
.splice(0, 20)
.map((sf) => {
return sf.toString();
}).join('\n');

// log with logging service
loggingService.error({ message, url, stack: stackString });

});

throw error;
}

}

auth.service.ts

@Injectable()
export class UserAuthService {
login(emailAddress: string, password: string): Observable<boolean> {
if (this.isAuthenticated()) {
return Observable.of(true);
}

return Observable.create(observer => {
this.http.get('http://someurl/login')
.map(res => res.json())
.subscribe(
data => {
observer.next(this.isAuthorized);
observer.complete();
}, err => {
observer.error(err);
}
);
});
}

}

我的组件.ts

import { UserAuthService } from '../services/auth.service';

@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent {
constructor(private authService: UserAuthService) {}

handleLogin() {
this.authService.login(formValues.emailAddress, formValues.password)
.subscribe(res => {
console.log('Logged In');
}, err => {
console.log('Logging Failed');
// Global Error DOESN'T fire here as the Error has been handled
});
}

handleLoginPart2() {
this.authService.login(formValues.emailAddress, formValues.password)
.subscribe(res => {
console.log('Logged In');
}); // Global Error does fire here as the Error has NOT been handled
}
}

最佳答案

我自己解决了这个问题,方法是创建一个继承自 HttpHttpClient

通过这样做,我能够优雅地处理错误。

http-client.service.ts

import { ConnectionBackend, Http, RequestOptions, RequestOptionsArgs, Response } from '@angular/http';

@Injectable()
export class HttpClient extends Http {
http;

constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}

get(url, options?: RequestOptionsArgs): Observable<Response> {
return super.get(url, options)
.catch(this.handleError);
}

private handleError(errorRes: Response | any) {
return Observable.throw(retError);
}
}

关于javascript - Angular 2 - 全局错误处理程序仅在未捕获错误时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52736181/

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