Help us understand the problem. What is going on with this article?

Rubyで独自例外を定義する

More than 1 year has passed since last update.

===環境===

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away