1 28 package org.jruby; 29 30 import java.io.PrintStream ; 31 32 import org.jruby.javasupport.JavaObject; 33 import org.jruby.runtime.Block; 34 import org.jruby.runtime.CallbackFactory; 35 import org.jruby.runtime.ObjectAllocator; 36 import org.jruby.runtime.builtin.IRubyObject; 37 38 39 public class NativeException extends RubyException { 40 41 private final Throwable cause; 42 public static final String CLASS_NAME = "NativeException"; 43 private final Ruby runtime; 44 45 public NativeException(Ruby runtime, RubyClass rubyClass, Throwable cause) { 46 super(runtime, rubyClass, cause.getClass().getName()+": "+cause.getMessage()); 47 this.runtime = runtime; 48 this.cause = cause; 49 } 50 51 public static RubyClass createClass(Ruby runtime, RubyClass baseClass) { 52 RubyClass exceptionClass = runtime.defineClass(CLASS_NAME, baseClass, ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR); 55 56 CallbackFactory callbackFactory = runtime.callbackFactory(NativeException.class); 57 exceptionClass.defineMethod("cause", 58 callbackFactory.getMethod("cause")); 59 60 return exceptionClass; 61 } 62 63 public IRubyObject cause(Block unusedBlock) { 64 return getRuntime().getModule("JavaUtilities").callMethod(getRuntime().getCurrentContext(), 65 "wrap", 66 JavaObject.wrap(getRuntime(), cause)); 67 } 68 69 public IRubyObject backtrace() { 70 IRubyObject rubyTrace = super.backtrace(); 71 if (rubyTrace.isNil()) 72 return rubyTrace; 73 RubyArray array = (RubyArray) rubyTrace; 74 StackTraceElement [] stackTrace = cause.getStackTrace(); 75 for (int i=stackTrace.length-1; i>=0; i--) { 76 StackTraceElement element = stackTrace[i]; 77 String line = element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getClassName() + "." + element.getMethodName() + "'"; 78 RubyString string = runtime.newString(line); 79 array.unshift(string); 80 } 81 return rubyTrace; 82 } 83 84 public void printBacktrace(PrintStream errorStream) { 85 super.printBacktrace(errorStream); 86 errorStream.println("Complete Java stackTrace"); 87 cause.printStackTrace(errorStream); 88 } 89 } 90 | Popular Tags |