Javascript Angular 2-仅在未捕获错误时执行全局错误处理程序
在我的Angular应用程序中,有一个全局错误处理程序和一个负责进行Javascript Angular 2-仅在未捕获错误时执行全局错误处理程序,javascript,angular,typescript,error-handling,angular2-services,Javascript,Angular,Typescript,Error Handling,Angular2 Services,在我的Angular应用程序中,有一个全局错误处理程序和一个负责进行http调用的服务,返回类型为可观察的。有些服务已经明确地处理了错误,有些则没有 对于那些尚未捕获的对象,全局错误(具有类“CustomErrorHandler”)运行良好。对于已经被优雅地处理和捕获的服务调用,全局错误似乎不会触发 我的问题:是否有方法执行全局错误处理,而不管http服务调用是否已处理 自定义错误处理程序.service.ts @Injectable() export class CustomErrorHand
http
调用的服务,返回类型为可观察的。有些服务已经明确地处理了错误,有些则没有
对于那些尚未捕获的对象,全局错误(具有类“CustomErrorHandler”)运行良好。对于已经被优雅地处理和捕获的服务调用,全局错误似乎不会触发
我的问题:是否有方法执行全局错误处理,而不管http服务调用是否已处理
自定义错误处理程序.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;
}
}
@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);
}
);
});
}
}
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
}
}
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);
}
}
auth.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;
}
}
@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);
}
);
});
}
}
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
}
}
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);
}
}
通过创建一个继承自Http
的HttpClient
,我自己就能够解决这个问题
通过这样做,我能够优雅地处理错误
http client.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;
}
}
@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);
}
);
});
}
}
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
}
}
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);
}
}
从'@angular/Http'导入{ConnectionBackend,Http,RequestOptions,RequestOptionsArgs,Response};
@可注射()
导出类HttpClient扩展Http{
http;
构造函数(后端:ConnectionBackend,defaultOptions:RequestOptions){
超级(后端,默认选项);
}
获取(url,选项?:RequestOptionsArgs):可观察{
返回super.get(url、选项)
.接住(这个.把手错误);
}
私有句柄错误(错误:响应|任何){
返回可观察的抛出(retError);
}
}