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

}

 

RxJS之catchError

继续抛出异常

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

}

RxJS之catchError

重新尝试

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

}

RxJS之catchError

 

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2018-03-28
  • 2021-09-23
  • 2021-10-04
  • 2021-06-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案