在我的角2应用程序中,我有一个带有http.get方法的服务,该方法返回一个可观察的。
campaign.service.ts
public getCampaign(campaignId: string): Observable<Campaign> {
return this.http.get(this.campaignsUrl + '/' + campaignId, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || body || {};
}
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}然后在我的组件中调用它,如下所示:
campaign.component.ts
this.campaignService.getCampaign(paramId)
.subscribe(
obj => {
// do something
},
() => {
// handle error here
}
});但是,如果http.get调用返回HTTP500,则我从未在服务类中访问过.catch(...)部分。控制台输出一个未察觉的异常。
GET http://localhost:9001/api/v1/campaigns/4175edc4 500 (Internal Server Error)
EXCEPTION: Response with status: 500 Internal Server Error for URL: http://localhost:9001/api/v1/campaigns/4175edc4
Uncaught Response {_body: "{"message":"invalid input syntax for uuid: \"4175edc4\""}", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…}我在这里做错了什么?
发布于 2017-01-07 06:52:03
角2遵循Fetch规范,即只有在请求操作出现问题时才抛出错误。。如果返回错误响应,它不会抛出(因为错误响应仍然是有效的响应)。
您需要检查response.ok属性,以确保它不是404或500等等。
发布于 2020-07-04 11:20:53
如果声明的函数没有在对象的上下文中声明,则为它们分配全局上下文。因此,当我们希望我们的闭包(内部函数)引用父对象之一时,我们要么保留对象的值,要么将对象绑定到函数。
试试这个:
.catch(this.handleError.bind(this));https://stackoverflow.com/questions/40699562
复制相似问题