gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:48 26 4
gpt4 key购买 nike

我想在我的全局异常处理程序中捕获 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);
});
}

}

这当然是行不通的,因为 throw 之后的代码没有被执行。
但是抛出的异常也没有被捕获,可能是因为这是在可观察对象中完成的。

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

最佳答案

您需要返回从头开始创建的新可观察对象:

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

}

关于Angular 2 在派生类中捕获可观察到的 http 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209940/

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