/
DefaultErrorHandler.java
316 lines (275 loc) · 12.3 KB
/
DefaultErrorHandler.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
* Copyright (C) 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ro.pippo.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.pippo.core.route.Route;
import ro.pippo.core.route.RouteContext;
import ro.pippo.core.util.StringUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* DefaultErrorHandler is the core ExceptionHandler that integrates with
* the TemplateEngine & ContentTypeEngines. It generates a representation
* of an exception or error result.
*
* @author Decebal Suiu
* @author James Moger
*/
public class DefaultErrorHandler implements ErrorHandler {
private static final Logger log = LoggerFactory.getLogger(DefaultErrorHandler.class);
private static final String MESSAGE = "message";
private Application application;
private final Map<Class<? extends Exception>, ExceptionHandler> exceptionHandlers;
public DefaultErrorHandler(Application application) {
this.application = application;
this.exceptionHandlers = new HashMap<>();
setExceptionHandler(StatusCodeException.class, new StatusCodeExceptionHandler(this));
}
@Override
public void setExceptionHandler(Class<? extends Exception> exceptionClass, ExceptionHandler exceptionHandler) {
exceptionHandlers.put(exceptionClass, exceptionHandler);
}
/**
* Returns an ExceptionHandler registered for this exception type.
* If no handler is found it returns null and the default handle
* (this class) is used.
*
* @param exception
* @return an exception handler or null
*/
@Override
public ExceptionHandler getExceptionHandler(Exception exception) {
Class<? extends Exception> exceptionClass = exception.getClass();
if (!exceptionHandlers.containsKey(exceptionClass)) {
Class<?> superClass = exceptionClass.getSuperclass();
while (superClass != null) {
if (exceptionHandlers.containsKey(superClass)) {
ExceptionHandler exceptionHandler = exceptionHandlers.get(superClass);
exceptionHandlers.put(exceptionClass, exceptionHandler);
return exceptionHandler;
}
superClass = superClass.getSuperclass();
}
// avoid superclass traversal in the future if we didn't find a handler
exceptionHandlers.put(exceptionClass, null);
}
return exceptionHandlers.get(exceptionClass);
}
@Override
public void handle(int statusCode, RouteContext routeContext) {
checkForRecursion(routeContext);
routeContext.status(statusCode);
// start with the content type specified for the response
String contentType = routeContext.getResponse().getContentType();
if (StringUtils.isNullOrEmpty(contentType)) {
if (!StringUtils.isNullOrEmpty(routeContext.getRequest().getAcceptType())) {
String acceptType = routeContext.getRequest().getAcceptType();
if (acceptType.startsWith(HttpConstants.ContentType.TEXT_HTML)
|| acceptType.startsWith(HttpConstants.ContentType.TEXT_XHTML)) {
// exception during a browser request
contentType = HttpConstants.ContentType.TEXT_HTML;
}
}
if (StringUtils.isNullOrEmpty(contentType)) {
// unspecified so negotiate a content type based on the request
routeContext.negotiateContentType();
// retrieve the negotiated type
contentType = routeContext.getResponse().getContentType();
}
}
if (StringUtils.isNullOrEmpty(contentType)) {
log.debug("No accept type nor content type specified! Defaulting to text/html.");
renderHtml(statusCode, routeContext);
} else if (contentType.equals(HttpConstants.ContentType.TEXT_HTML)) {
// render an html page
renderHtml(statusCode, routeContext);
} else {
// render an object representation
ContentTypeEngine engine = application.getContentTypeEngine(contentType);
if (engine == null) {
log.warn("No registered content type engine for '{}'", contentType);
renderHtml(statusCode, routeContext);
} else {
Error error = prepareError(statusCode, routeContext);
try {
routeContext.getResponse().contentType(engine.getContentType()).send(error);
} catch (Exception e) {
log.error("Unexpected error generating '{}' as '{}'!", Error.class.getName(), contentType, e);
routeContext.status(HttpConstants.StatusCode.INTERNAL_ERROR);
routeContext.send(application.getMessages().get("pippo.statusCode500", routeContext));
}
}
}
}
protected void renderHtml(int statusCode, RouteContext routeContext) {
if (application.getTemplateEngine() == null) {
renderDirectly(routeContext);
} else {
String template = getTemplateForStatusCode(statusCode);
if (template == null) {
log.debug("There is no {} template for status code '{}'", application.getTemplateEngine().getClass()
.getSimpleName(), statusCode);
renderDirectly(routeContext);
} else {
try {
Error error = prepareError(statusCode, routeContext);
Map<String, Object> bindings = error.asMap();
bindings.putAll(prepareTemplateBindings(statusCode, routeContext));
routeContext.setLocals(bindings);
routeContext.render(template);
} catch (Exception e) {
log.error("Unexpected error rendering your '{}' template!", template, e);
handle(e, routeContext);
}
}
}
}
@Override
public void handle(Exception exception, RouteContext routeContext) {
checkForRecursion(routeContext);
ExceptionHandler exceptionHandler = getExceptionHandler(exception);
if (exceptionHandler != null) {
log.debug("Handling '{}' with '{}'", exception.getClass().getSimpleName(), exceptionHandler.getClass().getName());
exceptionHandler.handle(exception, routeContext);
return;
}
log.error(exception.getMessage(), exception);
if (routeContext.getResponse().isCommitted()) {
log.debug("The response has already been committed. Cannot use the exception handler.");
return;
}
String message = exception.getMessage();
if (!StringUtils.isNullOrEmpty(message) && !routeContext.getResponse().getLocals().containsKey(MESSAGE)) {
routeContext.setLocal(MESSAGE, message);
}
if (application.getPippoSettings().isDev()) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
routeContext.setLocal("stacktrace", stackTrace);
}
handle(HttpConstants.StatusCode.INTERNAL_ERROR, routeContext);
}
/**
* Render the result directly.
*
* @param routeContext
*/
protected void renderDirectly(RouteContext routeContext) {
StringBuilder content = new StringBuilder();
content.append("<html><body>");
content.append("<div>");
content.append("Cannot find a route for '");
content.append(routeContext.getRequestMethod());
content.append(" ");
content.append(routeContext.getRequestUri());
content.append("'</div>");
content.append("<div>Available routes:</div>");
content.append("<ul style=\" list-style-type: none; margin: 0; \">");
List<Route> routes = application.getRouter().getRoutes();
for (Route route : routes) {
content.append("<li>");
content.append(route.getRequestMethod());
content.append(" ");
content.append(route.getUriPattern());
content.append("</li>");
}
content.append("</ul>");
content.append("</body></html>");
routeContext.send(content);
}
/**
* Get the template bindings for the error response.
*
* @param routeContext
* @return bindings map
*/
protected Map<String, Object> prepareTemplateBindings(int statusCode, RouteContext routeContext) {
Map<String, Object> locals = new LinkedHashMap<>();
locals.put("applicationName", application.getApplicationName());
locals.put("applicationVersion", application.getApplicationVersion());
locals.put("runtimeMode", application.getPippoSettings().getRuntimeMode().toString());
if (application.getPippoSettings().isDev()) {
locals.put("routes", application.getRouter().getRoutes());
}
return locals;
}
/**
* Prepares an Error instance for the error response.
*
* @param statusCode
* @param routeContext
* @return an Error
*/
protected Error prepareError(int statusCode, RouteContext routeContext) {
String messageKey = "pippo.statusCode" + statusCode;
Error error = new Error();
error.setStatusCode(statusCode);
error.setStatusMessage(application.getMessages().get(messageKey, routeContext));
error.setRequestMethod(routeContext.getRequestMethod());
error.setRequestUri(routeContext.getRequestUri());
error.setRequestUri(routeContext.getRequestUri());
error.setStacktrace(routeContext.getLocal("stacktrace"));
error.setMessage(routeContext.getLocal(MESSAGE));
return error;
}
protected String getTemplateForStatusCode(int statusCode) {
switch (statusCode) {
case HttpConstants.StatusCode.BAD_REQUEST:
return TemplateEngine.BAD_REQUEST_400;
case HttpConstants.StatusCode.UNAUTHORIZED:
return TemplateEngine.UNAUTHORIZED_401;
case HttpConstants.StatusCode.PAYMENT_REQUIRED:
return TemplateEngine.PAYMENT_REQUIRED_402;
case HttpConstants.StatusCode.FORBIDDEN:
return TemplateEngine.FORBIDDEN_403;
case HttpConstants.StatusCode.NOT_FOUND:
return TemplateEngine.NOT_FOUND_404;
case HttpConstants.StatusCode.METHOD_NOT_ALLOWED:
return TemplateEngine.METHOD_NOT_ALLOWED_405;
case HttpConstants.StatusCode.CONFLICT:
return TemplateEngine.CONFLICT_409;
case HttpConstants.StatusCode.GONE:
return TemplateEngine.GONE_410;
default:
case HttpConstants.StatusCode.INTERNAL_ERROR:
return TemplateEngine.INTERNAL_ERROR_500;
case HttpConstants.StatusCode.NOT_IMPLEMENTED:
return TemplateEngine.NOT_IMPLEMENTED_501;
case HttpConstants.StatusCode.OVERLOADED:
return TemplateEngine.OVERLOADED_502;
case HttpConstants.StatusCode.SERVICE_UNAVAILABLE:
return TemplateEngine.SERVICE_UNAVAILABLE_503;
}
}
private void checkForRecursion(RouteContext routeContext) {
Integer depth = routeContext.removeLocal("__errorHandlerDepth");
if (depth == null) {
depth = 0;
}
depth += 1;
routeContext.setLocal("__errorHandlerDepth", depth);
if (depth > 2) {
throw new PippoRuntimeException("Recursion in error handler");
}
}
}