Angular - 何时处理Observable订阅中的错误 [英] Angular - When to handle errors in Observable's subscription

查看:715
本文介绍了Angular - 何时处理Observable订阅中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己正在使用最新Angular版本编写的主题和搜索网页,我发现大部分开发人员不处理订阅错误



我的问题是:何时需要处理可观察订阅中的错误?



没有错误处理:

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

带有错误处理:

  this.myService.observable $ .subscribe(
(data)=> {
// do data with data
},
err => ; {
//做错事件
}
);

我主要找到第一个版本,但... ...



不是处理订阅错误的问题?



这不会使代码更不稳固,可测试,更容易失败?

解决方案

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



现在让我们看看为什么在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',
        });
      }
    });

这篇关于Angular - 何时处理Observable订阅中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆