我有一小段代码,可以运行一些事务进行处理。每笔交易都标有一个交易号,该交易号由外部程序生成,不一定要排序。当我在处理代码中捕获到异常时,我会将其抛出到主类中,并将其记录下来以供以后复查。我想将事务编号添加到这个抛出的异常中。有没有可能在保持正确的堆栈跟踪的同时做到这一点?
例如:
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;
}
}
}发布于 2021-06-27 18:36:27
您可以编写一个从Exception扩展的Exception类并添加属性,就像这样:`公共类PaymentException扩展Exception {公共对象数据;
public PaymentException(Throwable cause) {
super(cause);
}
public void setData(Object o) {
data = o;
}
public Object getData() {
return data;
}}`
https://stackoverflow.com/questions/12568340
复制相似问题