program story

DRY 방식으로 루비의 구조 절에 여러 오류 클래스 전달

inputbox 2020. 8. 30. 08:15
반응형

DRY 방식으로 루비의 구조 절에 여러 오류 클래스 전달


루비에서 여러 유형의 예외를 구해야하는 코드가 있습니다.

begin
  a = rand
  if a > 0.5
    raise FooException
  else
    raise BarException
  end
rescue FooException, BarException
  puts "rescued!"
end

내가하고 싶은 것은 어떻게 든 어딘가에 구출하려는 예외 유형 목록을 저장하고 해당 유형을 rescue 절에 전달하는 것입니다.

EXCEPTIONS = [FooException, BarException]

그리고:

rescue EXCEPTIONS

이것이 가능 eval할까요 , 그리고 실제로 해킹 호출없이 가능 합니까? 나는 TypeError: class or module required for rescue clause위의 시도를 할 때 내가 보고 있다는 것을 감안할 희망적이지 않습니다 .


splat 연산자와 함께 배열을 사용할 수 있습니다 *.

EXCEPTIONS = [FooException, BarException]

begin
  a = rand
  if a > 0.5
    raise FooException
  else
    raise BarException
  end
rescue *EXCEPTIONS
  puts "rescued!"
end

위와 같이 배열에 상수를 사용하려는 경우 (와 함께 EXCEPTIONS) 정의 내에서 정의 할 수 없으며 다른 클래스에서 정의하는 경우에도 해당 네임 스페이스로 참조해야합니다. 실제로 상수 일 필요는 없습니다.


표시 연산자

표시 연산자 *는 해당 위치에서 배열을 "압축 해제"하여

rescue *EXCEPTIONS

같은 의미

rescue FooException, BarException

배열 리터럴 내에서 다음과 같이 사용할 수도 있습니다.

[BazException, *EXCEPTIONS, BangExcepion]

이것은

[BazException, FooException, BarException, BangExcepion]

또는 인수 위치

method(BazException, *EXCEPTIONS, BangExcepion)

method(BazException, FooException, BarException, BangExcepion)

[] 공허로 확장 :

[a, *[], b] # => [a, b]

루비 1.8과 루비 1.9의 차이점 중 하나는 nil.

[a, *nil, b] # => [a, b]       (ruby 1.9)
[a, *nil, b] # => [a, nil, b]  (ruby 1.8)

다음과 같은 경우에 적용될 것이므로 to_a정의 된 객체에주의하십시오 to_a.

[a, *{k: :v}, b] # => [a, [:k, :v], b]

다른 유형의 개체와 함께 자신을 반환합니다.

[1, *2, 3] # => [1, 2, 3]

방금이 문제가 발생하여 대체 솔루션을 찾았습니다. 경우에 당신 FooExceptionBarException모든 사용자 정의 예외 클래스가 될 것 그리고 그들은 모든 주제별로 관련이 특히 경우, 당신은 그들이 모든 같은 부모 클래스에서 상속은 부모 클래스를 구출 것입니다 귀하의 상속 계층 구조는 구조 할 수 있습니다.

For example I had three exceptions: FileNamesMissingError,InputFileMissingError, and OutputDirectoryError that I wanted to rescue with one statement. I made another exception class called FileLoadError and then set up the above three exceptions to inherit from it. I then rescued only FileLoadError.

Like this:

class FileLoadError < StandardError
end

class FileNamesMissingError < FileLoadError
end

class InputFileMissingError < FileLoadError
end

class OutputDirectoryError < FileLoadError
end

[FileNamesMissingError,
 InputFileMissingError,
 OutputDirectoryError].each do |error| 
   begin  
     raise error
   rescue FileLoadError => e
     puts "Rescuing #{e.class}."
   end 
end

참고URL : https://stackoverflow.com/questions/5781639/passing-multiple-error-classes-to-rubys-rescue-clause-in-a-dry-fashion

반응형