首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >合理处理ScriptException抛出的JSR223犀牛

合理处理ScriptException抛出的JSR223犀牛
EN

Stack Overflow用户
提问于 2011-04-05 19:07:36
回答 1查看 771关注 0票数 7

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

我使用Java6SE附带的内置版本的Rhino,通过JSR223 223的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,我不知道我将如何使用它,反正它不是一个公共类。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-06 14:23:04

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

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

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5557113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档