typescript Angular -何时处理Observable订阅中的错误

yfjy0ee7  于 2023-08-07  发布在  TypeScript
关注(0)|答案(3)|浏览(127)

我发现自己在使用最新的Angular版本编写的主题代码并搜索网络,我发现大多数开发人员都不处理subscription错误。
我的问题是:什么时候必须处理Observable订阅中的错误?
无错误处理:

  1. this.myService.observable$.subscribe(
  2. (data) => {
  3. // do stuff with data
  4. }
  5. );

字符串
使用错误处理:

  1. this.myService.observable$.subscribe(
  2. (data) => {
  3. // do stuff with data
  4. },
  5. err => {
  6. // do stuff with error
  7. }
  8. );


我基本上都能找到第一个版本,但是...
不处理订阅的错误不是一个问题吗?
这难道不会使代码不那么可靠、可测试、更容易失败吗?

guykilcj

guykilcj1#

为什么错误处理很重要click Me
现在让我们看看为什么在Observables中需要错误处理。

范例:

  1. this.service.send(this.shareData).subscribe(() => {
  2. // Here you are sure that the send has shared the data sucessFully
  3. }, (error) => {
  4. /* Now If you want to handle errors Like Front End Errors and Log this
  5. In your backEnd DB So solve it and fix it */
  6. /* Example below check error type is It from frontEnd and log error through Api */
  7. if(error.type !== 'API') {
  8. this.logService.log({
  9. Level: 2,
  10. Message: 'Failed to setFromDB',
  11. });
  12. }
  13. });

字符串

展开查看全部
44u64gxh

44u64gxh2#

处理错误以向用户提供反馈或退回到默认行为是一个很好的实践。
例如,如果您尝试联系REST服务,并且发生了通信,那么您可能希望通知用户有关连接问题或加载缓存数据。
或者如果REST服务返回错误。例如,您的应用程序是一个预订应用程序,用户正在执行订单,但一旦他提交订单,库存中就没有更多的项目。REST服务返回错误,您应该向用户显示没有更多项目。
在Angular Style Guide中:
数据管理的细节,如头、HTTP方法、缓存、错误处理和重试逻辑,与组件和其他数据使用者无关。
这意味着您应该从服务返回有意义的消息。

ojsjcaue

ojsjcaue3#

与您的问题无关,但以下是如何在Angular 16上处理订阅内部的错误:

  1. this.http.get(url).subscribe(
  2. {
  3. next: (data) =>
  4. {
  5. //do something
  6. },
  7. error: (error) =>
  8. {
  9. //handle error
  10. }
  11. }
  12. );

字符串

相关问题