【问题标题】:reasonable handling of ScriptException thrown by JSR223 Rhino合理处理 JSR223 Rhino 抛出的 ScriptException
【发布时间】:2011-04-06 22:23:04
【问题描述】:

我开始接触到原本非常有用的 JSR223 脚本环境的肮脏小秘密。

我正在使用 Java 6 SE 附带的内置 Rhino 版本,通过 JSR223 的 ScriptingEngine 等访问它。

当我得到一个由我导出到 Javascript 环境中的 Java 对象引起的异常时,它是一个 ScriptingException,它包装了一个 sun.org.mozilla.javascript.internal.WrappedException,它包装了我真正的异常(例如 UnsupportedOperationException 或其他)

ScriptingException 为 getFileName() 返回 null,为 getLineNumber() 返回 -1。 但是当我查看消息和调试器时,WrappedException 具有正确的文件名和行号,它只是没有通过 ScriptingException 的 getter 方法发布它。

太好了。 现在我该怎么办?我不知道我将如何使用 sun.org.mozilla.javascript.internal.wrappedException 反正它不是一个公共类。

【问题讨论】:

    标签: java exception rhino jsr223


    【解决方案1】:

    啊。 Java 6 的 Rhino 与 sun.org.mozilla.javascript.internal.EvaluatorException 做同样的事情(不通过 ScriptingException 的方法发布文件名/行号等),谁知道还有多少其他异常。

    我能想到的唯一合理的处理方法是使用反射。这是我的解决方案。

    void handleScriptingException(ScriptingException se)
    { 
        final Throwable t1 = se.getCause();
        String lineSource = null;
        String filename = null;
        Integer lineNumber = null;
    
        if (hasGetterMethod(t1, "sourceName"))
        {
            lineNumber = getProperty(t1, "lineNumber", Integer.class);
            filename = getProperty(t1, "sourceName", String.class);
            lineSource = getProperty(t1, "lineSource", String.class);
        }
        else
        {
            filename = se.getFileName();
            lineNumber = se.getLineNumber();
        }
        /* do something with this info */
    }
    
    static private Method getGetterMethod(Object object, String propertyName)
    {
        String methodName = "get"+getBeanSuffix(propertyName);
        try {
            Class<?> cl = object.getClass();
            return cl.getMethod(methodName);
        }
        catch (NoSuchMethodException e) { 
            return null;
            /* gulp */ 
        }
    }
    static private String getBeanSuffix(String propertyName) {
        return propertyName.substring(0,1).toUpperCase()
           +propertyName.substring(1);  
    }   
    static private boolean hasGetterMethod(Object object, String propertyName) 
    {
        return getGetterMethod(object, propertyName) != null;
    }
    static private <T> T getProperty(Object object, String propertyName, 
            Class<T> cl) {
        try {
            Object result = getGetterMethod(object, propertyName).invoke(object);
            return cl.cast(result);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多