我想提供一個拋出例外而不是直接拋出例外的函式。例如,而不是寫:
def foo() {
def result = command_result("foo");
if (!result) {
throw new Exception("Bla!");
}
return result;
}
我想寫這個:
def foo() {
return command_result("foo") ?: error("Bla!");
}
這需要error()定義一個函式:
def error(msg) {
throw new Exception(msg);
}
但是當然我現在error()在呼叫堆疊的頂部,所以如果我寫
try {
print(foo());
} catch(Exception error) {
print("ERROR: ${error.stackTrace.head()}: ${error}");
}
我會得到類似的東西
ERROR: Script1.error(Script1.groovy:19): java.lang.Exception: Bla!
為了擺脫error:19堆疊,我猜我可以只提取第二項,error.stackTrace但這將迫使我擁有一個通用try/catch塊。
是否可以在 Groovy 中提供這樣的功能(我想在 Java 中也是一樣的),即(重新)拋出一個例外,并從回溯中洗掉當前函式?
uj5u.com熱心網友回復:
使用 getStackTrace,然后洗掉您不想在那里的專案,然后使用 setSracTrace 在例外中更改它。
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#setStackTrace(java.lang.StackTraceElement[])
在 groovy 中,很難洗掉屬于最新呼叫的所有堆疊跟蹤元素。但是,您可以在執行此操作之前清理堆疊跟蹤(洗掉所有 groovy 內部專案):
def error(msg) {
def e = new Exception(msg)
e = org.codehaus.groovy.runtime.StackTraceUtils.sanitize(e)
//drop items with unknown source and drop first element of stacktrace
e.setStackTrace( e.getStackTrace().findAll{ it.getFileName() }.drop(1) as StackTraceElement[] )
throw e
}
def foo(x) {
return x ?: error("Bla!")
}
try{
foo(0)
}catch(e){
assert e.stackTrace[0].methodName=='foo'
e.printStackTrace()
}
注意:如果您在選單項中運行此代碼,groovyconsole必須View / Show Full Stack Trace禁用才能sanitize正常作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437710.html
上一篇:在嵌套的multiprocessing.Process上呼叫start后Python未引發例外
下一篇:為什么運行此代碼時出現錯誤?
