LoginSignup
4
3

More than 5 years have passed since last update.

Rubyで独自例外を定義する

Last updated at Posted at 2018-08-07

===環境===

osx 10.12.6
ruby 2.4.3

===独自例外の作成===

error_type.rb

class MyError1 < StandardError
end

===例外処理を明示的に分けたいときに便利===

example.rb

class InvalidAccountError < StandardError
 # アカウント情報が違う時にエラーを出したい。
end
class InvalidPageError < StandardError
 # アクセスするページがないときにエラーを出したい。
end

begin
  http     = Net::HTTP.start(host = "hogehoge.com", port = 80)
  req      =  Net::HTTP::Get.new("/")
  req.basic_auth(username, password)
  response = http.request(req)
  raise InvalidAccountError if response.code == "401"
  raise InvalidPageError if response.code == "404"
rescue InvalidAccountError => e
  "#{e.message}"
rescue InvalidPageError => e
  "#{e.message}"
end

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3