我需要建议处理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
时,所有社区事件都在发生|后端中的所有事件列表都在发生。
请帮忙^^
答案 0 :(得分:1)
订阅时,您使用Observer
模式进行订阅。因此,您传入的第一个函数
.subscribe(() => {} );
在Observable
调用.next(...)
时触发
之后,您可以提供另一个函数,只要Observable
调用.error(...)
如此
.subscribe(() => {}, (error) => { handleTheError(error); } );
this.http.get(...);
返回一个Observable
,它将因HTTP错误而触发.error(...)
我们还知道this.http.get(...)
完成或“错误”,并且它不是无止境的(永远不会完成)。因此,您可以将其作为一个承诺并按其进行操作。
async getMeSomething(...) {
try {
this.mydata = await this.http.get(...).toPromise();
}
catch(error) {
handleTheError(error)
}
}
但是我真正建议您使用Swagger作为后端,然后使用NSwagStudio生成API客户端类,因此您不必手动编写客户端或对其进行调整或处理错误赶上。我一直在使用它,它为我们节省了大量时间
答案 1 :(得分:0)
由于使用的是“ .subscribe”,因此可以直接在方法上创建自己的错误处理程序并捕获此类错误。
这是有关如何使用它的示例:
constructor(
private _suiteAPIService: SuitesAPIService,
private _testcaseService: TestcaseService,
public _tfsApiService: TfsApiService,
private _notificationService: NotificationService) { }
errorHandler(error: HttpErrorResponse) {
return observableThrowError(error.message || "Server Error")
}
public something = "something";
GetTestcasesFromSuiteSubscriber(Project, BuildNumber, SuiteId) {
this._suiteAPIService.GetTestResults(Project, BuildNumber, SuiteId).subscribe(
data => {
console.log(data);
this._testcaseService.ListOfTestcases = data;
//Notofication service to get data.
this._notificationService.TestcasesLoaded();
},
error => {
//Here we write som error
return this.something;
}
);
}