1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.executor;
17
18
19
20
21 public class ErrorContext {
22
23 private static final String LINE_SEPARATOR = System.lineSeparator();
24 private static final ThreadLocal<ErrorContext> LOCAL = new ThreadLocal<>();
25
26 private ErrorContext stored;
27 private String resource;
28 private String activity;
29 private String object;
30 private String message;
31 private String sql;
32 private Throwable cause;
33
34 private ErrorContext() {
35 }
36
37 public static ErrorContext instance() {
38 ErrorContext context = LOCAL.get();
39 if (context == null) {
40 context = new ErrorContext();
41 LOCAL.set(context);
42 }
43 return context;
44 }
45
46 public ErrorContext store() {
47 ErrorContextt.html#ErrorContext">ErrorContext newContext = new ErrorContext();
48 newContext.stored = this;
49 LOCAL.set(newContext);
50 return LOCAL.get();
51 }
52
53 public ErrorContext recall() {
54 if (stored != null) {
55 LOCAL.set(stored);
56 stored = null;
57 }
58 return LOCAL.get();
59 }
60
61 public ErrorContext resource(String resource) {
62 this.resource = resource;
63 return this;
64 }
65
66 public ErrorContext activity(String activity) {
67 this.activity = activity;
68 return this;
69 }
70
71 public ErrorContext object(String object) {
72 this.object = object;
73 return this;
74 }
75
76 public ErrorContext message(String message) {
77 this.message = message;
78 return this;
79 }
80
81 public ErrorContext sql(String sql) {
82 this.sql = sql;
83 return this;
84 }
85
86 public ErrorContext cause(Throwable cause) {
87 this.cause = cause;
88 return this;
89 }
90
91 public ErrorContext reset() {
92 resource = null;
93 activity = null;
94 object = null;
95 message = null;
96 sql = null;
97 cause = null;
98 LOCAL.remove();
99 return this;
100 }
101
102 @Override
103 public String toString() {
104 StringBuilder description = new StringBuilder();
105
106
107 if (this.message != null) {
108 description.append(LINE_SEPARATOR);
109 description.append("### ");
110 description.append(this.message);
111 }
112
113
114 if (resource != null) {
115 description.append(LINE_SEPARATOR);
116 description.append("### The error may exist in ");
117 description.append(resource);
118 }
119
120
121 if (object != null) {
122 description.append(LINE_SEPARATOR);
123 description.append("### The error may involve ");
124 description.append(object);
125 }
126
127
128 if (activity != null) {
129 description.append(LINE_SEPARATOR);
130 description.append("### The error occurred while ");
131 description.append(activity);
132 }
133
134
135 if (sql != null) {
136 description.append(LINE_SEPARATOR);
137 description.append("### SQL: ");
138 description.append(sql.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim());
139 }
140
141
142 if (cause != null) {
143 description.append(LINE_SEPARATOR);
144 description.append("### Cause: ");
145 description.append(cause.toString());
146 }
147
148 return description.toString();
149 }
150
151 }