2011-04-05 3 views
7

매우 유용한 JSR223 스크립팅 환경이 무엇인지에 대한 더러운 비밀을 다루기 시작했습니다.JSR223에 의해 throw 된 ScriptException에 대한 합리적인 처리 Rhino

JSR223의 ScriptingEngine 등을 통해 액세스하는 Java 6 SE와 함께 제공되는 Rhino의 기본 버전을 사용하고 있습니다. 나는 자바 스크립트 환경으로 내 보낸 자바 객체에 의해 발생하는 예외를 얻을 때

, 내 실제 예외입니다 ScriptingException 반환 널 (null)

(예 UnsupportedOperationException 또는 무엇이든)을 감싸는 sun.org.mozilla.javascript.internal.WrappedException를 래핑하는 ScriptingException입니다 getFileName()에 대해서는 getLineNumber()에 대해 -1을 반환합니다. 그러나 메시지와 디버거에서 WrappedException은 올바른 파일 이름과 줄 번호를 가지고 있지만 ScriptingException의 getter 메서드를 통해 게시하지 않습니다.

좋아요. 이제 어떻게해야합니까? 어쨌든 공개 클래스가 아닌 sun.org.mozilla.javascript.internal.wrappedException을 어떻게 사용할지 모르겠습니다.

답변

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; 
} 
관련 문제