admin
2021-07-28 c0269fcfa876b9c5cf309b2006462b4d09c5ef95
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package de.greenrobot.event.util;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
import android.util.Log;
import de.greenrobot.event.EventBus;
 
 
/**
 * Maps throwables to texts for error dialogs. Use Config to configure the mapping.
 * 
 * @author Markus
 */
public class ExceptionToResourceMapping {
 
    public final Map<Class<? extends Throwable>, Integer> throwableToMsgIdMap;
 
    public ExceptionToResourceMapping() {
        throwableToMsgIdMap = new HashMap<Class<? extends Throwable>, Integer>();
    }
 
    /** Looks at the exception and its causes trying to find an ID. */
    public Integer mapThrowable(final Throwable throwable) {
        Throwable throwableToCheck = throwable;
        int depthToGo = 20;
 
        while (true) {
            Integer resId = mapThrowableFlat(throwableToCheck);
            if (resId != null) {
                return resId;
            } else {
                throwableToCheck = throwableToCheck.getCause();
                depthToGo--;
                if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) {
                    Log.d(EventBus.TAG, "No specific message ressource ID found for " + throwable);
                    // return config.defaultErrorMsgId;
                    return null;
                }
            }
        }
 
    }
 
    /** Mapping without checking the cause (done in mapThrowable). */
    protected Integer mapThrowableFlat(Throwable throwable) {
        Class<? extends Throwable> throwableClass = throwable.getClass();
        Integer resId = throwableToMsgIdMap.get(throwableClass);
        if (resId == null) {
            Class<? extends Throwable> closestClass = null;
            Set<Entry<Class<? extends Throwable>, Integer>> mappings = throwableToMsgIdMap.entrySet();
            for (Entry<Class<? extends Throwable>, Integer> mapping : mappings) {
                Class<? extends Throwable> candidate = mapping.getKey();
                if (candidate.isAssignableFrom(throwableClass)) {
                    if (closestClass == null || closestClass.isAssignableFrom(candidate)) {
                        closestClass = candidate;
                        resId = mapping.getValue();
                    }
                }
            }
 
        }
        return resId;
    }
 
    public ExceptionToResourceMapping addMapping(Class<? extends Throwable> clazz, int msgId) {
        throwableToMsgIdMap.put(clazz, msgId);
        return this;
    }
 
}