aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/Exceptions.java
blob: e0cd54936d60688ab87efba5f5e01e1b7ea95038 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.di.componentgraph.core;

import java.util.Arrays;

class Exceptions {

    static <E extends Throwable> E removeStackTrace(E exception) {
        if (preserveStackTrace()) {
            return exception;
        } else {
            exception.setStackTrace(new StackTraceElement[0]);
            return exception;
        }
    }

    static boolean preserveStackTrace() {
        String preserve = System.getProperty("jdisc.container.preserveStackTrace");
        return (preserve != null && !preserve.isEmpty());
    }

    static Throwable cutStackTraceAtConstructor(Throwable throwable, StackTraceElement marker) {
        if (throwable != null && !preserveStackTrace()) {
            StackTraceElement[] stackTrace = throwable.getStackTrace();
            int upTo = stackTrace.length - 1;

            // take until ComponentNode is reached
            while (upTo >= 0 && !stackTrace[upTo].getClassName().equals(ComponentNode.class.getName())) {
                upTo--;
            }

            // then drop until <init> is reached
            while (upTo >= 0 && !stackTrace[upTo].getMethodName().equals("<init>")) {
                upTo--;
            }
            if (upTo < 0) {
                throwable.setStackTrace(new StackTraceElement[0]);
            } else {
                throwable.setStackTrace(Arrays.copyOfRange(stackTrace, 0, upTo));
            }

            cutStackTraceAtConstructor(throwable.getCause(), marker);
        }
        return throwable;
    }

}