Angular Global Exception Handler Does Not Work (Typescript)

时间:2017-06-14 10:27:48

标签: javascript angular typescript observable

I have setup a global event handler in Angular 4 (Typescript), but am unable to catch errors raised within the RX subscribe method for the onerror handler. The signin method returns an observable object based on a call to http.post which in turns calls Identity Server 4 (connect/token).

The global event handler does work. I have tested throwing exceptions and the handler catches the errors outside of subscribe methods.

Do you have any idea how I can get the global event handler to catch an error raised within the subscribe method for the onerror handler? I have tried "throw error" and "Observable.Throw ..." statements but neither works. I think the issue is that the exceptions are not propagated or is swallowed. I do not want to have to manually call the global event handler method in order to handle an error.

signin.ts

this.authentication.signin(this.model.userName, this.model.password)
        .subscribe(
       () => {
           // Optional strategy for refresh token through a scheduler.
           this.authentication.scheduleRefresh();

           // Gets the redirect URL from authentication service.
           // If no redirect has been set, uses the default.
           const redirect: string = this.authentication.redirectUrl
               ? this.authentication.redirectUrl
               : '/home';

           // Redirects the user.
           this.router.navigate([redirect]);
       },
       (error: any) => {

           const result: any = error.json();

           if (result == null) {
               throw error;
           }
           if (result.error !== "invalid_grant") {
               throw error;
           }

           this.error.error("Invalid user name or password");

       });

global.error.ts

export class GlobalErrorHandler implements ErrorHandler {
constructor(private injector: Injector) {
}

handleError(error: any) {
    //const loggingService = this.injector.get(LoggingService);
    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: any) => {
        const stackString = stackframes
            .splice(0, 20)
            .map(function (sf: any) {
                return sf.toString();
            }).join('\n');
        console.log({ message, url, stack: stackString });
        // log on the server
        //loggingService.log({ message, url, stack: stackString });
    });
    throw error;
}
}

0 个答案:

没有答案