From b8879197b2242d560accd7b3d9731b2e9a5ef56f Mon Sep 17 00:00:00 2001 From: kares Date: Tue, 17 Apr 2012 08:00:03 +0200 Subject: [PATCH] wrap StandardErrors into Rhino's JavaScriptException so they can be try-catched as JS "error" values (RedJS 0.3.0 compatibility) --- Gemfile | 2 +- lib/rhino/ruby.rb | 27 +++++++++++++++++++++------ spec/rhino/ruby_spec.rb | 24 ++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 7 deletions(-) diff --git a/Gemfile b/Gemfile index 98ee069..f9c19ef 100644 --- a/Gemfile +++ b/Gemfile @@ -2,4 +2,4 @@ source :rubygems gemspec -gem 'redjs', :git => 'git://github.com/cowboyd/redjs.git', :tag => "0.2.1", :group => :test \ No newline at end of file +gem 'redjs', :git => 'git://github.com/cowboyd/redjs.git', :tag => "0.3.0", :group => :test diff --git a/lib/rhino/ruby.rb b/lib/rhino/ruby.rb index 4a5e280..8beca4d 100644 --- a/lib/rhino/ruby.rb +++ b/lib/rhino/ruby.rb @@ -2,10 +2,6 @@ module Rhino module Ruby - def self.wrap_error(e) - JS::WrappedException.new(org.jruby.exceptions.RaiseException.new(e)) - end - # shared JS::Scriptable implementation module Scriptable @@ -173,12 +169,12 @@ module Rhino begin callable = if @callable.is_a?(UnboundMethod) - @callable.bind(Rhino.to_ruby(this)) + @callable.bind(Rhino.to_ruby(this)) # might end up as TypeError else @callable end result = callable.call(*rb_args) - rescue => e + rescue StandardError => e raise Ruby.wrap_error(e) # thus `try { } catch (e)` works in JS end Rhino.to_javascript(result, scope) @@ -229,6 +225,25 @@ module Rhino context ? context.cache(key, &block) : yield end + # "hack" for ruby errors so that they act as JS thrown objects + class Exception < JS::JavaScriptException + + def initialize(value) + super wrap_value(value) + end + + private + + def wrap_value(value) + value.is_a?(Object) ? value : Object.wrap(value) + end + + end + + def self.wrap_error(e) + Exception.new(e) + end + end RubyObject = Ruby::Object diff --git a/spec/rhino/ruby_spec.rb b/spec/rhino/ruby_spec.rb index 3f1eb1c..056a212 100644 --- a/spec/rhino/ruby_spec.rb +++ b/spec/rhino/ruby_spec.rb @@ -388,3 +388,27 @@ describe Rhino::Ruby::Constructor do end end + +describe Rhino::Ruby::Exception do + + it 'outcomes as ruby errors in function calls' do + klass = Class.new(Object) do + def foo(arg) + raise TypeError, "don't foo me with #{arg}" unless arg.is_a?(String) + end + end + rb_function = Rhino::Ruby::Function.wrap klass.new.method(:foo) + context = nil; scope = nil; this = nil; args = [ 42.to_java ].to_java + begin + rb_function.call(context, scope, this, args) + rescue java.lang.Exception => e + e.should be_a(Rhino::Ruby::Exception) + e.getValue.should be_a(Rhino::Ruby::Object) + e.value.unwrap.should be_a(TypeError) + e.value.unwrap.message == "don't foo me with 42" + else + fail "#{Rhino::Ruby::Exception} expected to be raised" + end + end + +end