将自定义消息添加到抛出的异常中,同时在 Java 中维护堆栈跟踪
2022-08-31 14:55:39
我有一小段代码,它通过一些事务进行处理。每个事务都标有事务编号,该编号由外部程序生成,不一定进行排序。当我在处理代码中捕获异常时,我会将其抛到主类并记录下来以供以后查看。我想将事务编号添加到此引发的异常中。是否可以在保持正确的堆栈跟踪的同时执行此操作?
例如:
public static void main(String[] args) {
try{
processMessage();
}catch(Exception E){
E.printStackTrace();
}
}
private static void processMessage() throws Exception{
String transNbr = "";
try{
transNbr = "2345";
throw new Exception();
}catch(Exception E){
if(!transNbr.equals("")){
//stack trace originates from here, not from actual exception
throw new Exception("transction: " + transNbr);
}else{
//stack trace gets passed correctly but no custom message available
throw E;
}
}
}