我正在从第三方jars中调用一个方法,它的类文件是我无法访问的。因此,在某些情况下,它会抛出异常日志,我希望动态地从当前日志中提取字符串。
这是引发异常的java程序方法。
public String runLayoutTest(final String xmlFile){
try{
String gettingValue = "novalue";
boolean errorFlag = perform("runLayoutTest", new Reporter.Reportable() {
@Override
public boolean run() throws Exception {
String layoutXml = null;
//current directory
Path currentRelativePath = Paths.get("");
String currentProjectPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + currentProjectPath);
System.out.println("layoutXml "+xmlFile);
String x = client.runLayoutTest(currentProjectPath+"\\Excel\\"+xmlFile);
System.out.println("******* x ********"+x);
setX(x);
return true;
}
});
gettingValue = getX();
return gettingValue;
}catch(Exception e){
System.out.println("**Any one rule in Layout is failed**");
//System.out.println(e.getMessage());
return getX();
}
} 在这里,客户机是第三方jar文件的一个对象,这在一些奇怪的情况下给我抛出了异常。
异常日志是
com.experitest.client.InternalException: Exception caught while executing runLayoutTest: {"rule_1":{"Exists":true},"rule_2":{"Exists":true,"EqualHeight":false},"rule_3":{"AlignedLeft":false}}
at com.experitest.client.JavaClientInternals.executeInternally(JavaClientInternals.java:234)
at com.experitest.client.Client.execute(Client.java:237)
at com.experitest.client.Client.runLayoutTest(Client.java:1475)
at com.igate.framework.NativeDriver$79.run(NativeDriver.java:2753)
at com.igate.framework.Reporter.action(Reporter.java:81)........从这个异常中,我想提取
runLayoutTest: {"rule_1":{"Exists":true},"rule_2":{"Exists":true,"EqualHeight":false},"rule_3":{"AlignedLeft":false}}就像一根绳子。
因此,是否有任何方法可以在发生这种字符串时动态地提取该字符串。我仍然不知道为什么我的捕捉方法没有被呼叫。
发布于 2016-02-16 11:50:50
我必须实现这段代码才能直接攻击可抛出的detailMessage。我不得不忽略所有扩展异常的类的层次结构,因为有人实现了与web组件重叠的可怕的getMessage方法。在JUnit中,无法定义单元测试用例,因为框架的异常总是试图将其错误代码转换为“会话”(web)语言.
public static Object getThrowableDetailMessage(Throwable throwable) {
try {
// Tiramos la puerta abajo y pedimos a Throwable que nos pase el código de error
Field f = Throwable.class.getDeclaredField("detailMessage");
f.setAccessible(true);
Object detailMessageFound = f.get(throwable);
return detailMessageFound;
} catch (SecurityException ex) {
//LOG
return null;
} catch (NoSuchFieldException e) {
//LOG
return null;
} catch (IllegalArgumentException e) {
//LOG
return null;
} catch (IllegalAccessException e) {
//LOG
return null;
}
}您还可以尝试用InternalException替换Throwable,并将反射保持在这个层次上。但就像已经有人指指点点。确保您的代码受到要检查的异常的影响。
我已经实现了所有可能的捕获,因为我想为每个人跟踪不同的日志。(用于总体调试和测试)
注意:我的代码已经在JDK 1.6_18下实现了
发布于 2016-02-16 12:06:28
在您的情况下,您可以只使用Exception.getMessage(),这将导致
在执行runLayoutTest:{“rule_1”:{“存在”:true},“rule_2”:{“存在”:真,"EqualHeight":false},“rule_3”:{“AlignedLeft”:false}时捕获的异常
下面可以用来获取json字符串。然后,您可以解析json以从json中获取所需的数据。
String message = e.getMessage();
int colonIndex = message.indexOf(":");
String json = null;
if (colonIndex != -1) {
json = message.substring(colonIndex + 1);
}请注意,在包装异常的情况下,此解决方案不起作用。
https://stackoverflow.com/questions/35431430
复制相似问题