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