1 | package com.framsticks.util; |
---|
2 | |
---|
3 | import java.util.ArrayList; |
---|
4 | import java.util.List; |
---|
5 | |
---|
6 | import com.framsticks.util.lang.Delimeted; |
---|
7 | import com.framsticks.util.lang.Pair; |
---|
8 | |
---|
9 | @SuppressWarnings("serial") |
---|
10 | public class FramsticksException extends RuntimeException { |
---|
11 | |
---|
12 | protected List<Pair<String, Object>> arguments; |
---|
13 | protected String message; |
---|
14 | |
---|
15 | public FramsticksException() { |
---|
16 | super("framsticks exception"); |
---|
17 | } |
---|
18 | |
---|
19 | public FramsticksException msg(String message) { |
---|
20 | this.message = message; |
---|
21 | return this; |
---|
22 | } |
---|
23 | |
---|
24 | public FramsticksException cause(Throwable cause) { |
---|
25 | initCause(cause); |
---|
26 | return this; |
---|
27 | } |
---|
28 | |
---|
29 | public FramsticksException arg(String header, Object argument) { |
---|
30 | if (arguments == null) { |
---|
31 | arguments = new ArrayList<>(); |
---|
32 | } |
---|
33 | arguments.add(new Pair<String, Object>(header, argument)); |
---|
34 | return this; |
---|
35 | } |
---|
36 | |
---|
37 | public StringBuilder getShortMessage(StringBuilder b) { |
---|
38 | if (message != null) { |
---|
39 | b.append(message); |
---|
40 | } else { |
---|
41 | b.append("?"); |
---|
42 | } |
---|
43 | if (arguments != null) { |
---|
44 | if (message != null) { |
---|
45 | b.append(" "); |
---|
46 | } |
---|
47 | Delimeted<Pair<String, Object>> d = new Delimeted<>(", ", ""); |
---|
48 | d.append(arguments.iterator()); |
---|
49 | |
---|
50 | b.append("(").append(d.build()).append(")"); |
---|
51 | } |
---|
52 | return b; |
---|
53 | } |
---|
54 | |
---|
55 | public String getMsg() { |
---|
56 | return message; |
---|
57 | } |
---|
58 | |
---|
59 | @Override |
---|
60 | public String getMessage() { |
---|
61 | StringBuilder b = new StringBuilder(); |
---|
62 | getShortMessage(b); |
---|
63 | Throwable cause = this.getCause(); |
---|
64 | while (cause != null) { |
---|
65 | b.append(" caused by: [").append(cause.getClass().getCanonicalName()).append(": "); |
---|
66 | if (cause instanceof FramsticksException) { |
---|
67 | ((FramsticksException) cause).getShortMessage(b); |
---|
68 | } else { |
---|
69 | b.append(cause.getMessage()); |
---|
70 | } |
---|
71 | b.append("]"); |
---|
72 | cause = cause.getCause(); |
---|
73 | } |
---|
74 | return b.toString(); |
---|
75 | } |
---|
76 | |
---|
77 | |
---|
78 | public static ExceptionHandler addArgumentHandler(final ExceptionHandler innerHandler, final String header, final Object argument) { |
---|
79 | return new ExceptionHandler() { |
---|
80 | @Override |
---|
81 | public void handle(FramsticksException exception) { |
---|
82 | innerHandler.handle(exception.arg(header, argument)); |
---|
83 | } |
---|
84 | }; |
---|
85 | } |
---|
86 | |
---|
87 | } |
---|