|
47 | 47 | import java.util.Collection; |
48 | 48 | import java.util.Comparator; |
49 | 49 | import java.util.LinkedHashSet; |
50 | | -import java.util.Map; |
51 | 50 | import java.util.Set; |
52 | 51 | import java.util.SortedSet; |
53 | | -import java.util.TreeMap; |
54 | 52 | import java.util.TreeSet; |
55 | 53 | import java.util.logging.Level; |
56 | 54 | import java.util.logging.Logger; |
@@ -122,35 +120,29 @@ public <T extends Throwable> ExceptionMapper<T> find(final Class<T> type) { |
122 | 120 |
|
123 | 121 | @SuppressWarnings("unchecked") |
124 | 122 | private <T extends Throwable> ExceptionMapper<T> find(final Class<T> type, final T exceptionInstance) { |
125 | | - |
126 | | - final Map<Integer, ExceptionMapper<T>> orderedMappers = new TreeMap<Integer, ExceptionMapper<T>>(); |
127 | | - |
| 123 | + ExceptionMapper<T> mapper = null; |
| 124 | + int minDistance = Integer.MAX_VALUE; |
128 | 125 | for (final ExceptionMapperType mapperType : exceptionMapperTypes) { |
129 | 126 | final int d = distance(type, mapperType.exceptionType); |
130 | | - if (d >= 0) { |
131 | | - orderedMappers.put(d, mapperType.mapper.getService()); |
132 | | - } |
133 | | - } |
134 | | - |
135 | | - if (orderedMappers.size() == 0) { |
136 | | - return null; |
137 | | - } |
138 | | - |
139 | | - if (exceptionInstance != null) { |
140 | | - for (final ExceptionMapper<T> mapper : orderedMappers.values()) { |
141 | | - if (mapper instanceof ExtendedExceptionMapper) { |
142 | | - final boolean mappable = ((ExtendedExceptionMapper<T>) mapper).isMappable(exceptionInstance); |
143 | | - if (mappable) { |
| 127 | + if (d >= 0 && d <= minDistance) { |
| 128 | + final ExceptionMapper<T> candidateMapper = mapperType.mapper.getService(); |
| 129 | + if (isMappable(exceptionInstance, candidateMapper)) { |
| 130 | + mapper = candidateMapper; |
| 131 | + minDistance = d; |
| 132 | + if (d == 0) { |
| 133 | + // slight optimization: if the distance is 0, it is already the best case, so we can exit |
144 | 134 | return mapper; |
145 | 135 | } |
146 | | - } else { |
147 | | - return mapper; |
148 | 136 | } |
149 | 137 | } |
150 | | - return null; |
151 | | - } else { |
152 | | - return orderedMappers.values().iterator().next(); |
153 | 138 | } |
| 139 | + return mapper; |
| 140 | + } |
| 141 | + |
| 142 | + private <T extends Throwable> boolean isMappable(T exceptionInstance, ExceptionMapper<T> mapper) { |
| 143 | + return exceptionInstance == null |
| 144 | + || !(mapper instanceof ExtendedExceptionMapper) |
| 145 | + || ((ExtendedExceptionMapper<T>) mapper).isMappable(exceptionInstance); |
154 | 146 | } |
155 | 147 |
|
156 | 148 | /** |
|
0 commit comments