Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you rescue from specific errors with messages in ruby?

Tags:

ruby

I'm trying to understand how errors propogate between classes in Ruby. I have this so far:

class User
  def charge
    puts "charging order soon"
    raise RuntimeError.new("This is a runtime error")
  rescue ArgumentError
    puts "should never gets here"
  end
end

class Runner
  def run
    begin
      User.new.charge
    rescue RuntimeError => e
      puts e.message
    end
  end
end

Runner.new.run

When I run this, I get this which seems right:

$ ruby errors.rb
charging order soon
This is a runtime error

Inside runner, can I rescue from the RuntimeError with a specific message? If I have multiple RuntimeErrors being raised around my application, is there any way for the Runner's rescue clause to be raised only for RuntimeErrors with specific messages?

like image 588
Jwan622 Avatar asked Mar 29 '17 23:03

Jwan622


1 Answers

See https://stackoverflow.com/a/23771227/2981429

If you call raise inside a rescue block, the last raised exception will be re-raised.

In your exception block, you can check the message and choose to re-raise or not:

begin
  User.new.charge
rescue RuntimeError => e
  case e.message
  when "This is a runtime error"
    # put your handler code here
  else
    raise # re-raise the last exception
  end
end

However if it's your goal to solely rescue errors that you yourself raise manually, then it's probably easier to define a custom error class instead:

class MyError < StandardError; end

Then instead of raise RuntimeError.new("message") use raise MyError.new("message"), and rescue it normally:

begin
  User.new.charge
rescue MyError => e
  # handler
end

This way you don't have to worry about your rescues interfering with the built-in exceptions.

like image 71
max pleaner Avatar answered Oct 11 '22 13:10

max pleaner