다음을 통해 공유


Observable.Catch<TSource, TException> 메서드(IObservable<TSource>, Func<TException, IObservable<TSource>>)

처리기에서 생성된 관찰 가능한 시퀀스를 사용하여 지정된 형식의 예외에 의해 종료되는 관찰 가능한 시퀀스를 계속합니다.

네임스페이스:System.Reactive.Linq
어셈블리: System.Reactive(System.Reactive.dll)

Syntax

'Declaration
<ExtensionAttribute> _
Public Shared Function Catch(Of TSource, TException As Exception) ( _
    source As IObservable(Of TSource), _
    handler As Func(Of TException, IObservable(Of TSource)) _
) As IObservable(Of TSource)
'Usage
Dim source As IObservable(Of TSource)
Dim handler As Func(Of TException, IObservable(Of TSource))
Dim returnValue As IObservable(Of TSource)

returnValue = source.Catch(handler)
public static IObservable<TSource> Catch<TSource, TException>(
    this IObservable<TSource> source,
    Func<TException, IObservable<TSource>> handler
)
where TException : Exception
[ExtensionAttribute]
public:
generic<typename TSource, typename TException>
where TException : Exception
static IObservable<TSource>^ Catch(
    IObservable<TSource>^ source, 
    Func<TException, IObservable<TSource>^>^ handler
)
static member Catch : 
        source:IObservable<'TSource> * 
        handler:Func<'TException, IObservable<'TSource>> -> IObservable<'TSource>  when 'TException : Exception
JScript does not support generic types and methods.

형식 매개 변수

  • TSource
    원본의 형식입니다.
  • TException
    예외의 형식입니다.

매개 변수

  • handler(핸들러)
    형식: System.Func<TException, IObservable<TSource>>
    다른 관찰 가능한 시퀀스를 생성하는 예외 처리기 함수입니다.

반환 값

형식: System.IObservable<TSource>
소스 시퀀스의 요소를 포함하는 관찰 가능한 시퀀스, 예외가 발생한 경우 처리기의 결과 관찰 가능한 시퀀스에 의해 생성된 요소가 뒤따릅니다.

사용 정보

Visual Basic 및 C#에서는 IObservable TSource> 형식의 모든 개체에서 이 메서드를 instance 메서드로 호출할 수 있습니다<. 인스턴스 메서드 구문을 사용하여 이 메서드를 호출할 경우에는 첫 번째 매개 변수를 생략합니다. 자세한 내용은 또는 를 참조하세요.

설명

catch 연산자는 처리기 함수에 지정된 예외와 동일한 형식의 예외가 발생할 때 구독에 추가 시퀀스를 도입하는 데 사용할 수 있습니다. 이는 추가 시퀀스를 생성하는 예외 처리기를 실행하는 Catch 연산자에 의해 수행됩니다. 소스 시퀀스가 예외 없이 완료될 경우 처리기가 실행되지 않습니다. 예외가 처리기 함수에 지정된 형식과 같지 않으면 해당 예외가 관찰자의 OnError 처리기로 전송됩니다. 이 항목의 예제 코드는 Catch 연산자를 보여 줍니다.

예제

다음 예제에서는 예외가 발생한 경우 catch 연산자를 사용하여 구독에 정수의 추가 시퀀스를 포함하는 방법을 보여 줍니다. throw된 예외는 예외 처리기 함수의 서명에 있는 예외와 동일한 형식이어야 합니다. 형식이 같지 않으면 관찰자에 대한 OnError 처리기가 예외 처리기 대신 실행됩니다.

using System;
using System.Collections.Generic;
using System.Reactive.Linq;

namespace Example
{

  class Program
  {

    static void Main()
    {
      //***********************************************************************************************//
      //*** sequence1 is generated from the enumerator returned by the RandomNumSequence function.  ***//
      //*** It will be combined with sequence2 using the Catch() operator only if there is an       ***//
      //*** exception thrown in sequence1 that is caught by the Catch() operator.                   ***//
      //***********************************************************************************************//
      IObservable<int> sequence1 = RandomNumSequence().ToObservable();


      //**************************************************************************************************************************//
      //*** In this catch operation, the exception handler for Observable::Catch will not be executed. This is because         ***//
      //*** sequence1 throws an InvalidOperationException which isn't of the NullReferenceException type specified in the      ***//
      //*** signature of ExNullRefHandler.                                                                                     ***//
      //***                                                                                                                    ***//
      //*** The InvalidOperationException will be caught by the OnError handler instead.                                       ***//
      //**************************************************************************************************************************//
      Console.WriteLine("==============================================================");
      Console.WriteLine("Calling Catch operator with NullReferenceException handler...");
      Console.WriteLine("==============================================================\n");
      sequence1.Catch((Func<NullReferenceException, IObservable<int>>)ExNullRefHandler)
        .Subscribe(i => Console.WriteLine(i),
                  (ex) => Console.WriteLine("\nException {0} in OnError handler\nException.Message : \"{1}\"\n\n", ex.GetType().ToString(), ex.Message));


      //**************************************************************************************************************************//
      //*** In this catch operation, the exception handler will be executed. Because InvalidOperationException thrown by       ***//
      //*** sequence1 is of the InvalidOperationException type specified in the signature of ExInvalidOpHandler().             ***//
      //**************************************************************************************************************************//

        Console.WriteLine("================================================================");
        Console.WriteLine("Calling Catch operator with InvalidOperationException handler...");
        Console.WriteLine("================================================================\n");
        sequence1.Catch((Func<InvalidOperationException, IObservable<int>>)ExInvalidOpHandler)
        .Subscribe(i => Console.WriteLine(i),
                  (ex) => Console.WriteLine("\nException {0} in OnError handler\nException.Message : \"{1}\"\n\n", ex.GetType().ToString(), ex.Message));


      Console.WriteLine("\nPress ENTER to exit...\n");
      Console.ReadLine();
    }




    //*******************************************************************************************************//
    //***                                                                                                 ***//
    //*** This method will yield a random sequence of 5 integers then throw an InvalidOperationException. ***//
    //***                                                                                                 ***//
    //*******************************************************************************************************//
    static IEnumerable<int> RandomNumSequence()
    {
      Random random = new Random();

      //************************************************//
      //*** Yield an a sequence of 5 random integers ***//
      //************************************************//
      for (int i = 0; i < 5; i++)
      {
        yield return random.Next(101);
      }

      //*********************************************************//
      //*** Then throw an InvalidOperationException exception ***//
      //*********************************************************//
      throw new InvalidOperationException("Some Exception Happened!");
    }



    //*********************************************************************************************************//
    //***                                                                                                   ***//
    //*** Simple catch handler for NullReferenceExceptions. This handler looks at the exception message and ***//
    //*** returns a sequence of int.                                                                        ***//
    //***                                                                                                   ***//
    //*********************************************************************************************************//
    static IObservable<int> ExNullRefHandler(NullReferenceException ex)
    {
      //***********************************************************************************************//
      //*** Sequence2 will be part of the resulting sequence if an exception is caught in sequence1 ***//
      //***********************************************************************************************//
      int[] sequence2 = { 0 };

      if (ex.Message == "Some Exception Happened!")
        sequence2 = new int[] { 5001, 5002, 5003, 5004 };

      return sequence2.ToObservable();
    }



    //************************************************************************************************************//
    //***                                                                                                      ***//
    //*** Simple catch handler for InvalidOperationExceptions. This handler looks at the exception message and ***//
    //*** returns a sequence of int.                                                                           ***//
    //***                                                                                                      ***//
    //************************************************************************************************************//
    static IObservable<int> ExInvalidOpHandler(InvalidOperationException ex)
    {
      //***********************************************************************************************//
      //*** Sequence2 will be part of the resulting sequence if an exception is caught in sequence1 ***//
      //***********************************************************************************************//
      int[] sequence2 = { 0 };

      if (ex.Message == "Some Exception Happened!")
        sequence2 = new int[] { 1001, 1002, 1003, 1004 };

      return sequence2.ToObservable();
    }
  }
}

다음은 예제 코드의 예제 출력입니다.

==============================================================
Calling Catch operator with NullReferenceException handler...
==============================================================

68
20
17
6
24

Exception System.InvalidOperationException in OnError handler
Exception.Message : "Some Exception Happened!"


================================================================
Calling Catch operator with InvalidOperationException handler...
================================================================

87
29
84
68
23
1001
1002
1003
1004

Press ENTER to exit...

참고 항목

참조

관찰 가능한 클래스

Catch 오버로드

System.Reactive.Linq 네임스페이스