我需要处理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客户端类,这样您就不必手动编写客户端或对其进行调整或处理错误捕获。我一直在使用它,它为我们节省了大量时间

08-03 16:30