且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-08-23 15:01:16

为什么错误处理重要点击我



现在让我们看看为什么在Observables中需要进行错误处理..



示例:

  this.service.send(this.shareData).subscribe(()=> {

//这里你确定发送有共享数据sucessFully

},(error)=> {

/ *现在如果你想处理错误像前端错误和记录这个
在你的backEnd DB所以解决它并修复它* /

/ *下面的示例检查错误类型是从frontEnd和日志错误通过Api * /

if(error.type !=='API'){
this.logService.log({
级别:2,
消息:'无法设置FromDB',
});
}
});


I have found myself working with code from themes written in latest Angular versions and searching the web, and I have found that the most part of devs don't handle the subscription error.

My question is: When do I have to handle the error in an Observable subscription?

Without error handling:

    this.myService.observable$.subscribe(
        (data) => {
            // do stuff with data
        }
    );

With error handling:

    this.myService.observable$.subscribe(
        (data) => {
            // do stuff with data
        },
        err => {
            // do stuff with error
        }
    );

I mostly find the first version, but...

Isn't an issue not to handle the errors of a subscription?

Doesn't this make the code less solid, testable and more prone to fail?

why is error handling important click Me

Now Lets see Why error handling is necessary in Observables..

Example:

this.service.send(this.shareData).subscribe(() => {

      // Here you are sure that the send has shared the data sucessFully

    }, (error) => {

      /* Now If you want to handle errors Like Front End Errors and Log this
         In your backEnd DB So solve it and fix it */

      /* Example below check error type is It from frontEnd and log error through Api */

      if(error.type !== 'API') {
        this.logService.log({
          Level: 2,
          Message: 'Failed to setFromDB',
        });
      }
    });