/
LemonErrorAttributes.java
78 lines (53 loc) · 2.47 KB
/
LemonErrorAttributes.java
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
74
75
76
77
78
package com.naturalprogrammer.spring.lemon.exceptions;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.context.request.RequestAttributes;
import com.naturalprogrammer.spring.lemon.exceptions.handlers.LemonExceptionHandler;
public class LemonErrorAttributes extends DefaultErrorAttributes {
private static final Log log = LogFactory.getLog(LemonErrorAttributes.class);
private final Map<String, LemonExceptionHandler<?>> handlers;
public LemonErrorAttributes(List<LemonExceptionHandler<?>> handlers) {
this.handlers = handlers.stream().collect(
Collectors.toMap(LemonExceptionHandler::getExceptionName,
Function.identity(), (handler1, handler2) -> {
return AnnotationAwareOrderComparator
.INSTANCE.compare(handler1, handler2) < 0 ?
handler1 : handler2;
}));
log.info("Created");
}
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map<String, Object> errorAttributes =
super.getErrorAttributes(requestAttributes, includeStackTrace);
addLemonErrorDetails(errorAttributes, requestAttributes);
return errorAttributes;
}
@SuppressWarnings("unchecked")
protected <T extends Throwable> void addLemonErrorDetails(
Map<String, Object> errorAttributes, RequestAttributes requestAttributes) {
Throwable ex = getError(requestAttributes);
LemonExceptionHandler<T> handler = null;
// find a handler for the exception
// if no handler is found,
// loop into for its cause (ex.getCause())
while (ex != null) {
handler = (LemonExceptionHandler<T>) handlers.get(ex.getClass().getSimpleName());
if (handler != null) // found a handler
break;
ex = ex.getCause();
}
if (handler != null) { // a handler is found
log.warn("Handling exception ", ex);
// Use the handler to add errors and update status
handler.putErrorDetails(errorAttributes, (T) ex);
}
}
}