Angular 2在派生类中捕获可观察的http错误

Jan*_*tze 1 exception-handling typescript angular2-observables angular

我想在我的全局异常处理程序中捕获HTTP错误.
异常处理程序适用于大多数异常,但不会捕获可观察的异常.我想要捕获的异常是HTTP异常.

这就是我尝试将HTTP可观察错误发送到异常处理程序的方法.

import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Http, Response, RequestOptionsArgs } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { HttpException } from '../exceptions/http-exception';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class HttpErrorService extends Http {

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

    request(url: string | Request, options?: RequestOptionsArgs) {
        return super.request(url, options).catch((error: Response) => {

            // Bypass lint.
            fail();
            function fail() {
                // Here I want to throw the exception to send it to the exception handler, but it should also execute return Observable.throw(error); So I can catch the exception at the subscribe.
                throw new HttpException(error);
            }

            return Observable.throw(error);
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用,因为抛出后的代码没有执行.
但抛出的异常也没有被捕获,可能是因为这是在一个可观察的情况下完成的.

有没有办法在全局异常处理程序中捕获异常,并且请求仍然可用于subscribe((res) => {}, (errRes) => {/*here*/})

Mac*_*der 6

您需要返回从头开始创建的新observable:

@Injectable()
export class HttpErrorService extends Http {

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

    request(url: string | Request, options?: RequestOptionsArgs) {
        return Observable.create(observer => {
            super.request(url, options).subscribe(
                res => observer.next(res), //simply passing success response
                err => { //error handling
                       console.log("global error handler");
                       observer.error(err); //passing error to the method which invoked request
                },
                () => observer.complete() //passing onComplete event to the method which invoked request
             );
        });
    }

}
Run Code Online (Sandbox Code Playgroud)