001// Licensed under the Apache License, Version 2.0 (the "License"); 002// you may not use this file except in compliance with the License. 003// You may obtain a copy of the License at 004// 005// http://www.apache.org/licenses/LICENSE-2.0 006// 007// Unless required by applicable law or agreed to in writing, software 008// distributed under the License is distributed on an "AS IS" BASIS, 009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 010// See the License for the specific language governing permissions and 011// limitations under the License. 012 013package org.apache.tapestry5.internal.services; 014 015import org.apache.tapestry5.ContextAwareException; 016import org.apache.tapestry5.ExceptionHandlerAssistant; 017import org.apache.tapestry5.SymbolConstants; 018import org.apache.tapestry5.beanmodel.services.*; 019import org.apache.tapestry5.commons.internal.util.TapestryException; 020import org.apache.tapestry5.commons.util.ExceptionUtils; 021import org.apache.tapestry5.http.Link; 022import org.apache.tapestry5.http.services.Request; 023import org.apache.tapestry5.http.services.Response; 024import org.apache.tapestry5.internal.InternalConstants; 025import org.apache.tapestry5.internal.structure.Page; 026import org.apache.tapestry5.ioc.ServiceResources; 027import org.apache.tapestry5.ioc.annotations.Symbol; 028import org.apache.tapestry5.ioc.internal.OperationException; 029import org.apache.tapestry5.json.JSONObject; 030import org.apache.tapestry5.runtime.ComponentEventException; 031import org.apache.tapestry5.services.ComponentClassResolver; 032import org.apache.tapestry5.services.ExceptionReporter; 033import org.apache.tapestry5.services.RequestExceptionHandler; 034import org.slf4j.Logger; 035 036import javax.servlet.http.HttpServletResponse; 037import java.io.IOException; 038import java.io.OutputStream; 039import java.net.URLEncoder; 040import java.util.Arrays; 041import java.util.HashMap; 042import java.util.List; 043import java.util.Map; 044import java.util.Map.Entry; 045 046/** 047 * Default implementation of {@link RequestExceptionHandler} that displays the standard ExceptionReport page. Similarly to the 048 * servlet spec's standard error handling, the default exception handler allows configuring handlers for specific types of 049 * exceptions. The error-page/exception-type configuration in web.xml does not work in Tapestry application as errors are 050 * wrapped in Tapestry's exception types (see {@link OperationException} and {@link ComponentEventException} ). 051 * 052 * Configurations are flexible. You can either contribute a {@link ExceptionHandlerAssistant} to use arbitrary complex logic 053 * for error handling or a page class to render for the specific exception. Additionally, exceptions can carry context for the 054 * error page. Exception context is formed either from the name of Exception (e.g. SmtpNotRespondingException {@code ->} ServiceFailure mapping 055 * would render a page with URL /servicefailure/smtpnotresponding) or they can implement {@link ContextAwareException} interface. 056 * 057 * If no configured exception type is found, the default exception page {@link SymbolConstants#EXCEPTION_REPORT_PAGE} is rendered. 058 * This fallback exception page must implement the {@link org.apache.tapestry5.services.ExceptionReporter} interface. 059 */ 060public class DefaultRequestExceptionHandler implements RequestExceptionHandler 061{ 062 private final RequestPageCache pageCache; 063 064 private final PageResponseRenderer renderer; 065 066 private final Logger logger; 067 068 private final String pageName; 069 070 private final Request request; 071 072 private final Response response; 073 074 private final ComponentClassResolver componentClassResolver; 075 076 private final LinkSource linkSource; 077 078 private final ExceptionReporter exceptionReporter; 079 080 // should be Class<? extends Throwable>, Object but it's not allowed to configure subtypes 081 private final Map<Class, Object> configuration; 082 083 /** 084 * @param configuration 085 * A map of Exception class and handler values. A handler is either a page class or an ExceptionHandlerAssistant. ExceptionHandlerAssistant can be a class 086 */ 087 @SuppressWarnings("rawtypes") 088 public DefaultRequestExceptionHandler(RequestPageCache pageCache, 089 PageResponseRenderer renderer, 090 Logger logger, 091 @Symbol(SymbolConstants.EXCEPTION_REPORT_PAGE) 092 String pageName, 093 Request request, 094 Response response, 095 ComponentClassResolver componentClassResolver, 096 LinkSource linkSource, 097 ServiceResources serviceResources, 098 ExceptionReporter exceptionReporter, 099 Map<Class, Object> configuration) 100 { 101 this.pageCache = pageCache; 102 this.renderer = renderer; 103 this.logger = logger; 104 this.pageName = pageName; 105 this.request = request; 106 this.response = response; 107 this.componentClassResolver = componentClassResolver; 108 this.linkSource = linkSource; 109 this.exceptionReporter = exceptionReporter; 110 111 Map<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant> handlerAssistants = new HashMap<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant>(); 112 113 for (Entry<Class, Object> entry : configuration.entrySet()) 114 { 115 if (!Throwable.class.isAssignableFrom(entry.getKey())) 116 throw new IllegalArgumentException(Throwable.class.getName() + " is the only allowable key type but " + entry.getKey().getName() 117 + " was contributed"); 118 119 if (entry.getValue() instanceof Class && ExceptionHandlerAssistant.class.isAssignableFrom((Class) entry.getValue())) 120 { 121 @SuppressWarnings("unchecked") 122 Class<ExceptionHandlerAssistant> handlerType = (Class<ExceptionHandlerAssistant>) entry.getValue(); 123 ExceptionHandlerAssistant assistant = handlerAssistants.get(handlerType); 124 if (assistant == null) 125 { 126 assistant = (ExceptionHandlerAssistant) serviceResources.autobuild(handlerType); 127 handlerAssistants.put(handlerType, assistant); 128 } 129 entry.setValue(assistant); 130 } 131 } 132 this.configuration = configuration; 133 } 134 135 /** 136 * Handles the exception thrown at some point the request was being processed 137 * 138 * First checks if there was a specific exception handler/page configured for this exception type, it's super class or super-super class. 139 * Renders the default exception page if none was configured. 140 * 141 * @param exception 142 * The exception that was thrown 143 */ 144 @SuppressWarnings({"rawtypes", "unchecked"}) 145 public void handleRequestException(Throwable exception) throws IOException 146 { 147 // skip handling of known exceptions if there are none configured 148 if (configuration.isEmpty()) 149 { 150 renderException(exception); 151 return; 152 } 153 154 Throwable cause = exception; 155 156 // Depending on where the error was thrown, there could be several levels of wrappers.. 157 // For exceptions in component operations, it's OperationException -> ComponentEventException -> <Target>Exception 158 159 // Throw away the wrapped exceptions first 160 while (cause instanceof TapestryException) 161 { 162 if (cause.getCause() == null) break; 163 cause = cause.getCause(); 164 } 165 166 Class<?> causeClass = cause.getClass(); 167 if (!configuration.containsKey(causeClass)) 168 { 169 // try at most two level of superclasses before delegating back to the default exception handler 170 causeClass = causeClass.getSuperclass(); 171 if (causeClass == null || !configuration.containsKey(causeClass)) 172 { 173 causeClass = causeClass.getSuperclass(); 174 if (causeClass == null || !configuration.containsKey(causeClass)) 175 { 176 renderException(exception); 177 return; 178 } 179 } 180 } 181 182 Object[] exceptionContext = formExceptionContext(cause); 183 Object value = configuration.get(causeClass); 184 Object page = null; 185 ExceptionHandlerAssistant assistant = null; 186 if (value instanceof ExceptionHandlerAssistant) 187 { 188 assistant = (ExceptionHandlerAssistant) value; 189 // in case the assistant changes the context 190 List context = Arrays.asList(exceptionContext); 191 page = assistant.handleRequestException(exception, context); 192 exceptionContext = context.toArray(); 193 } else if (!(value instanceof Class)) 194 { 195 renderException(exception); 196 return; 197 } else page = value; 198 199 if (page == null) return; 200 201 try 202 { 203 if (page instanceof Class) 204 page = componentClassResolver.resolvePageClassNameToPageName(((Class) page).getName()); 205 206 Link link = page instanceof Link 207 ? (Link) page 208 : linkSource.createPageRenderLink(page.toString(), false, exceptionContext); 209 210 if (request.isXHR()) 211 { 212 OutputStream os = response.getOutputStream("application/json;charset=UTF-8"); 213 214 JSONObject reply = new JSONObject(); 215 reply.in(InternalConstants.PARTIAL_KEY).put("redirectURL", link.toRedirectURI()); 216 217 os.write(reply.toCompactString().getBytes("UTF-8")); 218 219 os.close(); 220 221 return; 222 } 223 224 // Normal behavior is just a redirect. 225 226 response.sendRedirect(link); 227 } 228 // The above could throw an exception if we are already on a render request, but it's 229 // user's responsibility not to abuse the mechanism 230 catch (Exception e) 231 { 232 logger.warn("A new exception was thrown while trying to handle an instance of {}.", 233 exception.getClass().getName(), e); 234 // Nothing to do but delegate 235 renderException(exception); 236 } 237 } 238 239 private void renderException(Throwable exception) throws IOException 240 { 241 logger.error("Processing of request failed with uncaught exception: {}", exception, exception); 242 243 // In the case where one of the contributed rules, above, changes the behavior, then we don't report the 244 // exception. This is just for exceptions that are going to be rendered, real failures. 245 exceptionReporter.reportException(exception); 246 247 // TAP5-233: Make sure the client knows that an error occurred. 248 249 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 250 251 String rawMessage = ExceptionUtils.toMessage(exception); 252 253 // Encode it compatibly with the JavaScript escape() function. 254 255 String encoded = URLEncoder.encode(rawMessage, "UTF-8").replace("+", "%20"); 256 257 response.setHeader("X-Tapestry-ErrorMessage", encoded); 258 259 Page page = pageCache.get(pageName); 260 261 org.apache.tapestry5.services.ExceptionReporter rootComponent = (org.apache.tapestry5.services.ExceptionReporter) page.getRootComponent(); 262 263 // Let the page set up for the new exception. 264 265 rootComponent.reportException(exception); 266 267 renderer.renderPageResponse(page); 268 } 269 270 /** 271 * Form exception context either from the name of the exception, or the context the exception contains if it's of type 272 * {@link ContextAwareException} 273 * 274 * @param exception 275 * The exception that the context is formed for 276 * @return Returns an array of objects to be used as the exception context 277 */ 278 @SuppressWarnings({"unchecked", "rawtypes"}) 279 protected Object[] formExceptionContext(Throwable exception) 280 { 281 if (exception instanceof ContextAwareException) return ((ContextAwareException) exception).getContext(); 282 283 Class exceptionClass = exception.getClass(); 284 // pick the first class in the hierarchy that's not anonymous, probably no reason check for array types 285 while ("".equals(exceptionClass.getSimpleName())) 286 exceptionClass = exceptionClass.getSuperclass(); 287 288 // check if exception type is plain runtimeException - yes, we really want the test to be this way 289 if (exceptionClass.isAssignableFrom(RuntimeException.class)) 290 return exception.getMessage() == null ? new Object[0] : new Object[]{exception.getMessage().toLowerCase()}; 291 292 // otherwise, form the context from the exception type name 293 String exceptionType = exceptionClass.getSimpleName(); 294 if (exceptionType.endsWith("Exception")) exceptionType = exceptionType.substring(0, exceptionType.length() - 9); 295 return new Object[]{exceptionType.toLowerCase()}; 296 } 297 298}