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

时间:2017-07-20 08:55:36

标签: angular typescript exception-handling angular2-observables

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

这就是我尝试将HTTP observable错误发送到异常处理程序的方法。

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);
        });
    }

}

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

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

2 个答案:

答案 0 :(得分: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
             );
        });
    }

}

答案 1 :(得分:2)

您可以简单地注入全局错误处理程序并在其上调用handleError

export class HttpErrorService extends Http {

    constructor(errorHandler: ErrorHandler, backend: XHRBackend...) {
        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...
                const error = new HttpException(error);
                errorHandler.handleError(error); //<----------------- here!
            }

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