拦截错误和订阅

时间:2016-04-28 10:30:33

标签: angular

我有一个问题,以正确的方式订阅我的http拦截器。我有以下内容:

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
     return super.post(url,body, {headers: customHeaders}).catch(err =>{
            console.log('Error caught in POST at '+url);
            return Observable.of(err);
        });
    }

哪个好 - 每次发布时都会记录错误。但是,如果我尝试在其他组件中捕获错误,请执行以下操作:

this.http.post('someurl','somestring')
    .subscribe(
        success=>{
            console.log('success: ',success);
        },
        error=>{
            console.log('error: ',error);
        }
    )

现在,当POST中出现错误时,我的控制台日志会打印出来:

Error caught in POST at someurl
success: //errorobject here//

然而,我期待这个:

Error caught in POST at someurl
error: //errorobject here//

我做错了什么?

2 个答案:

答案 0 :(得分:1)

我认为它应该是throw err而不是Observable.of(err)

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
     return super.post(url,body, {headers: customHeaders}).catch(err =>{
            console.log('Error caught in POST at '+url);
            throw err;
        });
    }

答案 1 :(得分:1)

我会使用Observable.throw代替Observable.of

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
  return super.post(url,body, {headers: customHeaders}).catch(err =>{
        console.log('Error caught in POST at '+url);
        return Observable.throw(err); // <--------------
    });
}

Observable.of返回“成功”的可观察对象,因此它将由subscribe内的成功回调处理。