我需要处理Web应用程序前端错误的建议。
当我调用服务以根据Web应用程序中的社区get
社区时,我希望它捕获错误。例如用于捕获类似404的错误。
根据提供的ID,有一项获取社区的服务。
getCommunity(id: number) {
return this.http.get(`${this.api}/communities/` + id + ``);
}
在
events.ts
文件中调用的 setCommunityBaseUrl() {
this.listingService.getCommunity(environment.communityId).subscribe((data: any) => {
this.communityUrl = data.url + `/` + data.domain;
});
}
id
在环境中提供。假设总共有20个社区。当我提供id = 1
时,将出现根据community = 1
的事件。export const environment = {
production: ..,
version: 'v2',
apiUrl: '...',
organization: '...',
websiteTitle: '...',
communityId: 1,
googleMapsApiKey: '...'
};
问题是,当我提供
id = null
时,所有社区事件都在发生。后端中的所有事件列表都在发生。请帮忙^^
最佳答案
订阅时,您使用Observer
模式进行订阅。所以您传入的第一个函数
.subscribe(() => {} );
当
Observable
调用.next(...)
时触发然后,您可以提供另一个函数,该函数将在
Observable
调用.error(...)
时触发所以
.subscribe(() => {}, (error) => { handleTheError(error); } );
this.http.get(...);
返回一个Observable
,它将在出现HTTP错误时触发.error(...)
我们还知道
this.http.get(...)
已完成或出现“错误”,它不是无止境的(永远不会完成)。因此,您可以兑现 promise ,并像兑现 promise 一样进行操作。async getMeSomething(...) {
try {
this.mydata = await this.http.get(...).toPromise();
}
catch(error) {
handleTheError(error)
}
}
但是我真正建议您使用Swagger作为后端,然后使用NSwagStudio生成API客户端类,这样您就不必手动编写客户端或对其进行调整或处理错误捕获。我一直在使用它,它为我们节省了大量时间