• 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);
        });
      }
    
    }

     

     

  • 相关阅读:
    模拟一个弹出层
    mysql去重
    java 使用map返回多个对象组装
    java替换包含html标签
    java 给指定时间加上天数or给当前日期加天数
    js下载文件 阿星小栈
    Redis中Set集合命令 阿星小栈
    Mysql查询不为null值和字段为null 阿星小栈
    php求今天、昨天、明天时间戳的方法 阿星小栈
    PHP百分数转小数,php 小数转换百分数函数 阿星小栈
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/9035370.html
Copyright © 2020-2023  润新知