异常 java获取异常下的所有子异常

1

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
public class App {
    public static void main(String[] args) {
        create_throwable();
    }
    public static void create_throwable() {
        try {
            Exception e1 = new RuntimeException("Exception 1111111111111");
            Exception e2 = new RuntimeException("Exception 2222222222", e1);
            Exception e3 = new RuntimeException("Exception 33333333333", e2);
            Exception e4 = new RuntimeException("Exception 4444444444444", e3);
            Exception e5 = new RuntimeException("Exception 5555555555", e4);
            throw e5;
        } catch (Exception e) {
            Map map = new LinkedHashMap();
            get_throwable_map(e, map);
            for (Object key : map.keySet()) {
                System.out.println(key + " " + map.get(key));
            }
        }
    }
    private static void get_throwable_map(Throwable e, Map map) {
        if (e == null || map == null) return;
        int suffix = 1;
        if (map != null && map.keySet().size() > 0) {
            int max = (Integer) map.keySet().stream()
                    .map(s -> Integer.parseInt(s.toString().replace("errorMsg_", "").replace("stackTrace_", "")))
                    .max(Comparator.comparing(x -> ((Integer) x))).get();
            suffix = ++max;
        }
        map.put("errorMsg_" + suffix, e.getMessage());
        map.put("stackTrace_" + suffix, e.getStackTrace() != null ? Arrays.toString(e.getStackTrace()) : "");
        if (e.getCause() != null) {
            get_throwable_map(e.getCause(), map);
        }
    }
}
posted @ 2023-01-13 18:09  一只桔子2233  阅读(22)  评论(0编辑  收藏  举报