我们如何在java中提取一些异常的细节。
使用getMessage()
方法,我能够获取详细的异常消息,我只想要一些细节,例如会话信息:,会话ID:,该异常。
注意:
具体而言,我使用selenium.NoSuchElementException
答案 0 :(得分:0)
我只使用带有捕获组的正则表达式...当更高版本的Selenium更改其异常消息格式时,这可能会失败,但这是您可以从异常中提取的唯一方法。
另一种选择是从其他来源获取会话ID ...就像驱动程序...... RemoteWebDriver.getSessionId()
中的异常的正则表达式示例try {
throw new NoSuchElementException(
"no such element (Session info: chrome=40.0.2214.111) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 30.05 seconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00' System info: host: 'AS-Ramesh', ip: '*******', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_17' Session ID: 0e85209c610382395e8dee65a9766bd2 Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\\Users\\rameshp\\AppData\\Local\\Temp\\scoped_dir27484_24934}, rotatable=false, locationContextEnabled=true, version=40.0.2214.111, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]");
} catch (NoSuchElementException e) {
Pattern sessionId = Pattern.compile(".*\\(Session info: (.*?)\\).*Session ID: (\\w+).*");
Matcher m = sessionId.matcher(e.getMessage());
if (m.matches()) {
System.out.println(m.group(1)); // chrome=40.0.2214.111
System.out.println(m.group(2)); // 0e85209c610382395e8dee65a9766bd2
}
}