zoukankan      html  css  js  c++  java
  • RxJS之catchError

    Catches errors on the observable to be handled by returning a new observable or throwing an error.

    返回新的可观察对象

    import { Component, OnInit } from '@angular/core';
    import { of } from 'rxjs/observable/of';
    import { map, catchError, retry } from 'rxjs/operators';
    
    @Component({
      selector: 'app-error',
      templateUrl: './error.component.html',
      styleUrls: ['./error.component.css']
    })
    export class ErrorComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        of('Leo', 'Raph', 'Mikey', 'Don').pipe(
          map(turtle => {
            if (turtle === 'Mikey') {
              throw new Error('出错了');
            }
            return turtle;
          }),
          catchError(err => of('Aioria', 'Mu'))
        ).subscribe(turtle => {
          console.log(turtle);
        });
      }
    
    }

    继续抛出异常

    import { Component, OnInit } from '@angular/core';
    import { of } from 'rxjs/observable/of';
    import { map, catchError, retry } from 'rxjs/operators';
    
    @Component({
      selector: 'app-error',
      templateUrl: './error.component.html',
      styleUrls: ['./error.component.css']
    })
    export class ErrorComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        of('Leo', 'Raph', 'Mikey', 'Don').pipe(
          map(turtle => {
            if (turtle === 'Mikey') {
              throw new Error('出错了');
            }
            return turtle;
          }),
          catchError(err => {
            throw new Error('继续抛出异常');
          })
        ).subscribe(turtle => {
          console.log(turtle);
        });
      }
    
    }

    重新尝试

    import { Component, OnInit } from '@angular/core';
    import { of } from 'rxjs/observable/of';
    import { map, catchError, retry } from 'rxjs/operators';
    
    @Component({
      selector: 'app-error',
      templateUrl: './error.component.html',
      styleUrls: ['./error.component.css']
    })
    export class ErrorComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        of('Leo', 'Raph', 'Mikey', 'Don').pipe(
          map(turtle => {
            if (turtle === 'Mikey') {
              throw new Error('出错了');
            }
            return turtle;
          }),
          retry(2),
          catchError(err => of('Aioria', 'Mu'))
        ).subscribe(turtle => {
          console.log(turtle);
        });
      }
    
    }

     

     

  • 相关阅读:
    一个php soap的错误记录
    Android 开发有哪些新技术出现?
    每个PHP开发者都应该看的书
    30 个 PHP 的 Excel 处理类
    PHP Session可能会引起并发问题
    PHP代码优化技巧大盘点
    分析和解析PHP代码的7大工具
    关于 PHP 7 你必须知道的五件事
    PHP也20岁了
    PHP高级特性二之文件处理
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/9035370.html
Copyright © 2011-2022 走看看