1
0
Fork 0
mirror of https://github.com/rubyjs/therubyrhino synced 2023-03-27 23:21:34 -04:00

wrap StandardErrors into Rhino's JavaScriptException so they can be try-catched as JS "error" values (RedJS 0.3.0 compatibility)

This commit is contained in:
kares 2012-04-17 08:00:03 +02:00
parent cf3f7767c8
commit b8879197b2
3 changed files with 46 additions and 7 deletions

View file

@ -2,4 +2,4 @@ source :rubygems
gemspec gemspec
gem 'redjs', :git => 'git://github.com/cowboyd/redjs.git', :tag => "0.2.1", :group => :test gem 'redjs', :git => 'git://github.com/cowboyd/redjs.git', :tag => "0.3.0", :group => :test

View file

@ -2,10 +2,6 @@
module Rhino module Rhino
module Ruby module Ruby
def self.wrap_error(e)
JS::WrappedException.new(org.jruby.exceptions.RaiseException.new(e))
end
# shared JS::Scriptable implementation # shared JS::Scriptable implementation
module Scriptable module Scriptable
@ -173,12 +169,12 @@ module Rhino
begin begin
callable = callable =
if @callable.is_a?(UnboundMethod) if @callable.is_a?(UnboundMethod)
@callable.bind(Rhino.to_ruby(this)) @callable.bind(Rhino.to_ruby(this)) # might end up as TypeError
else else
@callable @callable
end end
result = callable.call(*rb_args) result = callable.call(*rb_args)
rescue => e rescue StandardError => e
raise Ruby.wrap_error(e) # thus `try { } catch (e)` works in JS raise Ruby.wrap_error(e) # thus `try { } catch (e)` works in JS
end end
Rhino.to_javascript(result, scope) Rhino.to_javascript(result, scope)
@ -229,6 +225,25 @@ module Rhino
context ? context.cache(key, &block) : yield context ? context.cache(key, &block) : yield
end 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 end
RubyObject = Ruby::Object RubyObject = Ruby::Object

View file

@ -388,3 +388,27 @@ describe Rhino::Ruby::Constructor do
end end
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