this.apiService.getUser().subscribe(result => {
// do something with the result
}, error => {
if (error.status == 400) {
this.errorMessage = "Invalid request paramater.";
} else if (error.status == 403) {
this.errorMessage = "Insufficient priviliges for executing this method.";
} else {
this.errorMessage = "Unknown error";
}
// view the error message with a toast
});
此代码段来自我的webapp服务中的方法。 如果发生错误,例如错误状态403,那么我在浏览器的控制台中出现错误,应用程序阻止了webapp中的所有按钮。但是,如果我在组件的方法中导出此代码片段,则不再出现错误。 我的问题是,为什么我只能在组件中而不是在服务中捕获/处理错误?
注意:apiService.getUser只执行如下请求:this.http.get(uri,headers,params,null);
public getUser(): Observable<HttpResponse<User>> {
let uri = `/users/current`;
let headers = new HttpHeaders();
let params = new HttpParams();
return this.sendRequest<User>('get', uri, headers, params, null);
}
private sendRequest<T>(method: string, uri: string, headers: HttpHeaders, params: HttpParams, body: any): Observable<HttpResponse<T>> {
if (method === 'get') {
return this.http.get<T>(this.domain + uri, { headers: headers.set('Accept', 'application/json'), params: params, observe: 'response' });
}