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

     

     

  • 相关阅读:
    myeclipse 配置svn
    windows下 将tomcat做成服务,并于oracle后启动
    局部内部类为什么只能访问final局部变量,对于成员变量却可以随便访问?
    使用cmd查看windows端口占用情况,并关闭应用
    生成javadoc文档
    JNI以及JNA使用
    自定义标签-java
    dwr框架应用
    Hadoop生态圈简介
    tomcat之日志记录
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/9035370.html
Copyright © 2011-2022 走看看