Ruby 및 / 또는 Rails에서 사용자 정의 오류 유형을 정의 할 위치는 어디입니까?
Ruby 라이브러리 (gem) 또는 Ruby on Rails 애플리케이션에서 사용자 정의 오류 유형을 정의하는 가장 좋은 방법이 있습니까? 구체적으로 특별히:
- 프로젝트에서 구조적으로 어디에 속합니까? 관련 모듈 / 클래스 정의와 함께 인라인 된 별도의 파일?
- 때 설정 어떤 규칙이 있는가 에 때 하지 않는 새로운 오류 유형을 만들 수는?
라이브러리마다 작업 방식이 다르며 실제 패턴을 발견하지 못했습니다. 일부 라이브러리는 항상 사용자 정의 오류 유형을 사용하지만 다른 라이브러리는 전혀 사용하지 않습니다. 일부는 StandardError를 확장하는 모든 오류가 있고 다른 일부는 중첩 된 계층이 있습니다. 일부는 빈 클래스 정의이고 다른 일부는 모든 종류의 영리한 트릭을 가지고 있습니다.
아, 그리고이 "오류 유형"이라고 부르는 느낌이 모호하기 때문에 이것이 의미하는 바는 다음과 같습니다.
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
보석
이런 식으로 예외를 정의하는 것을 여러 번 보았습니다.
gem_dir / lib / gem_name / exceptions.rb
다음과 같이 정의됩니다.
module GemName
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
end
Ruby on Rails의 경우
lib / 폴더에 exceptions.rb라는 파일 아래에 두십시오.
module Exceptions
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
end
그리고 당신은 이것을 다음과 같이 사용할 것입니다 :
raise Exceptions::InvalidUsername
프로젝트에 응집력있는 소스 파일을 가지려면 클래스에서 오류를 발생시키고 다른 곳에서는 던질 수없는 오류를 정의해야한다고 생각합니다.
일부 계층 구조는 도움이 될 수 있습니다. 네임 스페이스는 중복 문자열을 유형 이름에서 벗어나게하는 데 유용하지만 맛이 더 중요합니다. 앱에 적어도 하나 이상의 사용자 지정 예외 유형이 있으면 차별화 할 필요가 없습니다. '의도적'과 '우발적'예외 사례 사이.
레일에서 app/errors
디렉토리 를 만들 수 있습니다
# app/errors/foo_error.rb
class FooError < StandardError; end
스프링 / 서버를 다시 시작하면 픽업해야합니다
여러 사용자 정의 오류 클래스에 대해 Rails 4.1.10에서 자동로드가 예상대로 작동하도록하려면 각각에 대해 별도의 파일을 지정해야합니다. 이것은 동적으로 다시로드하여 개발에서 작동해야합니다.
이것은 최근 프로젝트에서 오류를 설정하는 방법입니다.
에 lib/app_name/error/base.rb
module AppName
module Error
class Base < StandardError; end
end
end
다음과 같은 후속 사용자 정의 오류에서 lib/app_name/error/bad_stuff.rb
module AppName
module Error
class BadStuff < ::AppName::Error::Base; end
end
end
그런 다음 다음을 통해 오류를 호출 할 수 있어야합니다.
raise AppName::Error::BadStuff.new("Bad stuff just happened")
This is an old question, but I wanted to share how I'm handling custom errors in Rails, including attaching error messages, testing, and how to handle this with ActiveRecord
models.
Creating Custom Error
class MyClass
# create a custome error
class MissingRequirement < StandardError; end
def my_instance_method
raise MyClass::MissingRequirement, "My error msg" unless true
end
end
Testing (minitest)
test "should raise MissingRequirement if ____ is missing"
# should raise an error
error = assert_raises(MyClass::MissingRequirement) {
MyClass.new.my_instance_method
}
assert error.message = "My error msg"
end
With ActiveRecord
I think it's worth noting that if working with an ActiveRecord
model, a popular pattern is to add an error to the model as described below, so that your validations will fail:
def MyModel < ActiveRecord::Base
validate :code_does_not_contain_hyphens
def code_does_not_contain_hyphens
errors.add(:code, "cannot contain hyphens") if code.include?("-")
end
end
When validations are run, this method will piggy-back onto ActiveRecord's ActiveRecord::RecordInvalid
error class and will cause validations to fail.
Hope this helps!
참고URL : https://stackoverflow.com/questions/5200842/where-to-define-custom-error-types-in-ruby-and-or-rails
'Programing' 카테고리의 다른 글
Clojure에서 목록 위에 벡터를 사용해야하는 경우와 다른 방법은 무엇입니까? (0) | 2020.06.20 |
---|---|
오라클 시퀀스의 현재 값을 증가시키지 않고 검색하는 방법은 무엇입니까? (0) | 2020.06.20 |
최종 정적 및 정적 최종의 차이점 (0) | 2020.06.20 |
.net의 거래 (0) | 2020.06.20 |
IIS7에서 폴더 및 확장마다 정적 콘텐츠 캐시를 구성하는 방법은 무엇입니까? (0) | 2020.06.20 |