2

I'm trying to handle loading invalid YAML data in Ruby, but seem to be unable to rescue exceptions raised by psych.

This is some example code to demonstrate the issue I'm having:

require 'yaml'
begin
    YAML.load('&*%^*')
rescue
    puts "Rescued"
end

And the exception:

# ruby test.rb
/usr/lib64/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>): did not find expected alphabetic or numeric character while scanning an anchor at line 1 column 1 (Psych::SyntaxError)
    from /usr/lib64/ruby/1.9.1/psych.rb:203:in `parse_stream'
    from /usr/lib64/ruby/1.9.1/psych.rb:151:in `parse'
    from /usr/lib64/ruby/1.9.1/psych.rb:127:in `load'
    from test.rb:3:in `<main>'
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
phemmer
  • 6,882
  • 3
  • 33
  • 31
  • On a side note, I'd suggest you don't use `YAML.load` with any user expected data, given the fact all the recent rails YAML and JSON related vulnerabilities that allowed a malicious user to do Remote Execution Exploits. – Jasdeep Singh Feb 03 '13 at 20:11
  • Did you get any solution for this issue?? other than catching exception.. – shajin Dec 16 '13 at 15:51
  • @shajin I did what is in the accepted solution, `rescue SyntaxError`, and not all of `Exception`. Not the greatest, but better than having to rescue everything. – phemmer Dec 16 '13 at 16:01

2 Answers2

9

The inheritance for SyntaxError is:

SyntaxError < ScriptError < Exception

rescue without parameters only catches StandardError which is a subclass of Exception:

StandardError < Exception

So, if you want to catch the Syntax errors from Yaml.load, you must rescue SyntaxError => e or to catch all errors using rescue Exception => e.

Leo Correa
  • 19,131
  • 2
  • 53
  • 71
  • 2
    Also [`Psych::SyntaxError` is a subclass of `::SyntaxError`](https://github.com/tenderlove/psych/blob/v1.3.4/lib/psych/syntax_error.rb#L2) which is why this applies to this case. (Although subclassing `::SyntaxError` does seem like an odd decision). – matt Feb 04 '13 at 00:24
5

See Begin Rescue not catching error. It is possible to rescue Syntax Errors, but not recommended. This is why you need to jump through the extra hoop of typing "rescue SyntaxError".

Community
  • 1
  • 1
Reck
  • 7,966
  • 2
  • 20
  • 24