public final void showError(@NotNull String message, @NotNull Throwable e) { if (getProject().isDisposed()) { return; } while (e instanceof InvocationTargetException) { if (e.getCause() == null) { break; } e = e.getCause(); } ErrorInfo info = new ErrorInfo(); info.myMessage = info.myDisplayMessage = message; info.myThrowable = e; configureError(info); if (info.myShowMessage) { showErrorPage(info); } if (info.myShowLog) { LOG.error( LogMessageEx.createEvent( info.myDisplayMessage, info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable), new Attachment(myFile))); } else { LOG.info(info.myDisplayMessage + "\n" + info.myMessage, info.myThrowable); } }
/** * Method called to create a "default instance" of the bean, currently only needed for obtaining * default field values which may be used for suppressing serialization of fields that have "not * changed". * * @param fixAccess If true, method is allowed to fix access to the default constructor (to be * able to call non-public constructor); if false, has to use constructor as is. * @return Instance of class represented by this descriptor, if suitable default constructor was * found; null otherwise. */ public Object instantiateBean(boolean fixAccess) { AnnotatedConstructor ac = _classInfo.getDefaultConstructor(); if (ac == null) { return null; } if (fixAccess) { ac.fixAccess(); } try { return ac.getAnnotated().newInstance(); } catch (Exception e) { Throwable t = e; while (t.getCause() != null) { t = t.getCause(); } if (t instanceof Error) throw (Error) t; if (t instanceof RuntimeException) throw (RuntimeException) t; throw new IllegalArgumentException( "Failed to instantiate bean of type " + _classInfo.getAnnotated().getName() + ": (" + t.getClass().getName() + ") " + t.getMessage(), t); } }
/** If the exception is wrapped, unwrap it. */ public static Throwable getActualException(Throwable e) { if (e instanceof ExecutionException) e = e.getCause(); if (e instanceof MBeanException || e instanceof RuntimeMBeanException || e instanceof RuntimeOperationsException || e instanceof ReflectionException) { Throwable t = e.getCause(); if (t != null) return t; } return e; }
// tries to get a message from a Throwable. Something there's a message and sometimes there's not. private static String getMessage(Throwable throwable) { String message = throwable.getMessage(); if (!GUtil.isTrue(message)) { message = String.format("%s (no error message)", throwable.getClass().getName()); } if (throwable.getCause() != null) { message += "\nCaused by: " + getMessage(throwable.getCause()); } return message; }
static void optionalTest() { // 不要这样,这与!=null没什么区别 Optional<String> stringOptional = Optional.of("alibaba"); if (stringOptional.isPresent()) { System.out.println(stringOptional.get().length()); } Optional<String> optionalValue = Optional.of("alibaba"); // 下面是推荐的常用操作 optionalValue.ifPresent(s -> System.out.println(s + " contains red")); // 增加到集合汇总 List<String> results = Lists.newArrayList(); optionalValue.ifPresent(results::add); // 增加到集合中,并返回操作结果 Optional<Boolean> added = optionalValue.map(results::add); // 无值的optional Optional<String> optionalString = Optional.empty(); // 不存在值,返回“No word” String result = optionalValue.orElse("No word"); // 没值,计算一个默认值 result = optionalString.orElseGet(() -> System.getProperty("user.dir")); // 无值,抛一个异常 try { result = optionalString.orElseThrow(NoSuchElementException::new); } catch (Throwable t) { t.getCause(); } }
public static void main(String[] args) { int errorCount = 0; for (int i = 0; i < NTESTS; i++) { try { System.out.println("Test " + i + ":"); test(i); } catch (Throwable e) { errorCount++; boolean first = true; do { System.err.println(first ? "Exception:" : "Caused by:"); first = false; e.printStackTrace(); Throwable nexte; nexte = e.getCause(); if (nexte == null) { // old JMX if (e instanceof MBeanException) nexte = ((MBeanException) e).getTargetException(); } e = nexte; } while (e != null); } } if (errorCount == 0) { System.out.println("All ModelMBean tests successfuly passed"); System.out.println("Bye! Bye!"); // JTReg doesn't like System.exit(0); return; } else { System.err.println("ERROR: " + errorCount + " tests failed"); System.exit(errorCount); } }
private static void printThrowable(OutputStream stream, Throwable throwable) { printBytes(stream, ("Exception " + throwable.toString()).getBytes()); printNewLine(stream); StackTraceElement[] stackTraceElements = throwable.getStackTrace(); for (int i = stackTraceElements.length - 1; i >= 0; i--) { StackTraceElement element = stackTraceElements[i]; printBytes(stream, element.getFileName().getBytes()); printBytes(stream, ":".getBytes()); printBytes(stream, String.valueOf(element.getLineNumber()).getBytes()); printNewLine(stream); } if (throwable.getCause() != null) { printBytes(stream, "Caused by:\n".getBytes()); printThrowable(stream, throwable.getCause()); } }
public static void raiseException(Throwable t) { error(t + ":\n" + StrUtils.join(t.getStackTrace(), "\n")); t = t.getCause(); if (t != null) error("Caused by " + t + ":\n" + StrUtils.join(t.getStackTrace(), "\n")); Execution.putOutput("exec.status", "exception"); exitCode = 1; }
/** * Finds root MondrianException in exception chain if exists, otherwise the input throwable. * * @param throwable Exception * @return Root exception */ public static Throwable rootThrowable(Throwable throwable) { Throwable rootThrowable = throwable.getCause(); if (rootThrowable != null && rootThrowable instanceof MondrianException) { return rootThrowable(rootThrowable); } return throwable; }
// -------------------------------------------------------- // exception handling // -------------------------------------------------------- public static Throwable unwrap(GroovyRuntimeException gre) { if (gre instanceof MissingPropertyExceptionNoStack) { MissingPropertyExceptionNoStack noStack = (MissingPropertyExceptionNoStack) gre; return new MissingPropertyException(noStack.getProperty(), noStack.getType()); } if (gre instanceof MissingMethodExceptionNoStack) { MissingMethodExceptionNoStack noStack = (MissingMethodExceptionNoStack) gre; return new MissingMethodException( noStack.getMethod(), noStack.getType(), noStack.getArguments(), noStack.isStatic()); } Throwable th = gre; if (th.getCause() != null && th.getCause() != gre) th = th.getCause(); if (th != gre && (th instanceof GroovyRuntimeException)) return unwrap((GroovyRuntimeException) th); return th; }
@SuppressWarnings("unchecked") private Tuple2<scala.collection.immutable.List<scala.collection.Map<String, Object>>, String> createTimedResults(PipeExecutionResult result) { try { return (Tuple2<scala.collection.immutable.List<scala.collection.Map<String, Object>>, String>) createTimedResults.invoke(result); } catch (Exception e) { Throwable root = e.getCause(); while (root.getCause() != null) { root = root.getCause(); } if (root != null) { throw new RuntimeException(root); } else { throw new RuntimeException("Unable to extract cypher results", e); } } }
/** * A loop driver for applying operations to all primary ClassNodes in our AST. Automatically skips * units that have already been processed through the current phase. */ public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException { // GRECLIPSE: start /*old{ Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator(); }*/ // newcode List primaryClassNodes = getPrimaryClassNodes(body.needSortedInput()); Iterator classNodes = primaryClassNodes.iterator(); // end while (classNodes.hasNext()) { SourceUnit context = null; try { ClassNode classNode = (ClassNode) classNodes.next(); context = classNode.getModule().getContext(); // GRECLIPSE get to the bottom of this - why are operations running multiple times that // should only run once? if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) { int offset = 1; Iterator<InnerClassNode> iterator = classNode.getInnerClasses(); while (iterator.hasNext()) { iterator.next(); offset++; } body.call(context, new GeneratorContext(this.ast, offset), classNode); } } catch (CompilationFailedException e) { // fall through, getErrorReporter().failIfErrors() will trigger } catch (NullPointerException npe) { throw npe; } catch (GroovyBugError e) { changeBugText(e, context); throw e; } catch (Exception e) { // check the exception for a nested compilation exception ErrorCollector nestedCollector = null; for (Throwable next = e.getCause(); next != e && next != null; next = next.getCause()) { if (!(next instanceof MultipleCompilationErrorsException)) continue; MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) next; nestedCollector = mcee.collector; break; } if (nestedCollector != null) { getErrorCollector().addCollectorContents(nestedCollector); } else { getErrorCollector().addError(new ExceptionMessage(e, configuration.getDebug(), this)); } } } getErrorCollector().failIfErrors(); }
/** * Configures the framework by reading its configuration file 'config/framework.xml' containing a * list with UrlConverters. */ protected final void configure(Element el) { try { description.fillFromXml("description", el); NodeList urlconverters = el.getElementsByTagName("urlconverter"); for (int i = 0; i < urlconverters.getLength(); i++) { Element element = (Element) urlconverters.item(i); UrlConverter uc; try { uc = (UrlConverter) Instantiator.getInstance(element, (Framework) this); } catch (NoSuchMethodException nsme) { uc = (UrlConverter) Instantiator.getInstance(element); } catch (ClassNotFoundException cnfe) { log.warn(org.mmbase.util.xml.XMLWriter.write(element) + " " + cnfe); continue; } catch (Throwable t) { log.error(org.mmbase.util.xml.XMLWriter.write(element) + ": " + t.getMessage(), t); if (t.getCause() != null) { log.error("Caused by: " + t.getCause().getMessage(), t.getCause()); } continue; } urlConverter.add(uc); } parDef = null; } catch (Throwable e) { log.error(e.getMessage(), e); } /* BasicUrlConverter buc = new BasicUrlConverter(this); if (! urlConverter.contains(buc)) { urlConverter.add(buc); } */ log.info( "Configured with " + el.getOwnerDocument().getDocumentURI() + " " + getClass() + " " + this); }
private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) { CmdlineRemoteProto.Message lastMessage = null; try { if (error != null) { Throwable cause = error.getCause(); if (cause == null) { cause = error; } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(out); try { cause.printStackTrace(stream); } finally { stream.close(); } final StringBuilder messageText = new StringBuilder(); messageText .append("Internal error: (") .append(cause.getClass().getName()) .append(") ") .append(cause.getMessage()); final String trace = out.toString(); if (!trace.isEmpty()) { messageText.append("\n").append(trace); } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause)); } else { CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS; if (myCanceled) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED; } else if (hadBuildErrors) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS; } else if (!markedUptodateFiles) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE; } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status)); } } catch (Throwable e) { lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e)); } finally { try { Channels.write(myChannel, lastMessage).await(); } catch (InterruptedException e) { LOG.info(e); } } }
/** * @param throwable Throwable * @return the root cause of this error */ private Throwable unwind(Throwable throwable) { Throwable t = null; if (throwable != null) { t = unwind(throwable.getCause()); if (t == null) { t = throwable; } } return t; }
// // Examine a single method to see if it raises SQLFeatureNotSupportedException. // private void vetMethod( Object candidate, Class iface, Method method, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { try { method.invoke(candidate, getNullArguments(method.getParameterTypes())); // it's ok for the method to succeed } catch (Throwable e) { if (!(e instanceof InvocationTargetException)) { recordUnexpectedError(candidate, iface, method, notUnderstoodList, e); } else { Throwable cause = e.getCause(); if (cause instanceof SQLFeatureNotSupportedException) { boolean isExcludable = isExcludable(method); if (!isExcludable) { StackTraceElement[] stack = cause.getStackTrace(); int i = 0; while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) { ++i; } while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) { ++i; } if (i == stack.length) { // cause.printStackTrace(); } unsupportedList.add( candidate.getClass().getName() + ": " + method + "@" + (i == stack.length ? "no source" : cause.getStackTrace()[i])); } else { } } else if (cause instanceof SQLException) { // swallow other SQLExceptions, caused by bogus args } else if (cause instanceof NullPointerException) { // swallow other NPEs, caused by bogus args } else if (cause instanceof ArrayIndexOutOfBoundsException) { // swallow these, caused by bogus args } else { recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause); } } } }
private void extractCauses(Throwable failure, List<Throwable> causes) { if (failure instanceof MultipleBuildFailures) { MultipleBuildFailures exception = (MultipleBuildFailures) failure; for (Throwable componentFailure : exception.getCauses()) { extractCauses(componentFailure, causes); } } else if (failure instanceof LocationAwareException) { causes.addAll(((LocationAwareException) failure).getReportableCauses()); } else { causes.add(failure.getCause()); } }
protected LinkedList<Throwable> getStack() { Throwable e = exception; LinkedList<Throwable> stack = new LinkedList<Throwable>(); while (e != null) { stack.addFirst(e); if (e instanceof NotFoundException) { status = HttpServletResponse.SC_NOT_FOUND; } if (e instanceof ServletException) { Throwable t = ((ServletException) e).getRootCause(); if (t == null) t = e.getCause(); e = t; } else if (e instanceof javax.servlet.jsp.JspException) { Throwable t = ((JspException) e).getRootCause(); if (t == null) t = e.getCause(); e = t; } else { e = e.getCause(); } } return stack; }
public static String getCompressedStackTrace( Throwable t, int frames_to_skip, int iMaxLines, boolean showErrString) { StringBuffer sbStackTrace = new StringBuffer(showErrString ? (t.toString() + "; ") : ""); StackTraceElement[] st = t.getStackTrace(); if (iMaxLines < 0) { iMaxLines = st.length + iMaxLines; if (iMaxLines < 0) { iMaxLines = 1; } } int iMax = Math.min(st.length, iMaxLines + frames_to_skip); for (int i = frames_to_skip; i < iMax; i++) { if (i > frames_to_skip) { sbStackTrace.append(", "); } String classname = st[i].getClassName(); String cnShort = classname.substring(classname.lastIndexOf(".") + 1); if (Constants.IS_CVS_VERSION) { if (STOP_AT_INITIALIZER && st[i].getClassName().equals("com.aelitis.azureus.ui.swt.Initializer")) { sbStackTrace.append("Initializer"); break; } // Formatted so it's clickable in eclipse sbStackTrace.append(st[i].getMethodName()); sbStackTrace.append(" ("); sbStackTrace.append(classname); sbStackTrace.append(".java:"); sbStackTrace.append(st[i].getLineNumber()); sbStackTrace.append(')'); } else { sbStackTrace.append("::"); sbStackTrace.append(st[i].getMethodName()); sbStackTrace.append("::"); sbStackTrace.append(st[i].getLineNumber()); } } Throwable cause = t.getCause(); if (cause != null) { sbStackTrace.append("\n\tCaused By: "); sbStackTrace.append(getCompressedStackTrace(cause, 0)); } return sbStackTrace.toString(); }
@Override public void log(final SVNLogType logType, final Throwable th, final Level logLevel) { if (th instanceof SSLHandshakeException) { final long time = System.currentTimeMillis(); if ((time - myPreviousTime) > ourMaxFrequency) { myPreviousTime = time; String info = myHelper.getAddInfo(); info = info == null ? "" : " (" + info + ") "; if (th.getCause() instanceof CertificateException) { PopupUtil.showBalloonForActiveComponent( "Subversion: " + info + th.getCause().getMessage(), MessageType.ERROR); } else { final String postMessage = "\nPlease check Subversion SSL settings (Settings | Version Control | Subversion | Network)"; PopupUtil.showBalloonForActiveComponent( "Subversion: " + info + th.getMessage() + postMessage, MessageType.ERROR); } } } if (shouldLog(logType)) { myLog.info(th); } }
private boolean canRetryDriverConnection(Exception e) { if (e instanceof DriverException && e.getMessage().contains("Connection thread interrupted")) return true; if (e instanceof NoHostAvailableException) { if (((NoHostAvailableException) e).getErrors().values().size() == 1) { Throwable cause = ((NoHostAvailableException) e).getErrors().values().iterator().next(); if (cause != null && cause.getCause() instanceof java.nio.channels.ClosedByInterruptException) { return true; } } } return false; }
private void dumpInnerCauses(StringBuilder sb, Throwable innerCause, int indent) { if (innerCause == null) { return; } for (int i = 0; i < indent; i++) { sb.append(INDENT_STRING); } sb.append("Caused by "); sb.append(innerCause.getClass().getName()); sb.append(": "); sb.append(innerCause.getMessage()); sb.append("\n"); dumpStackTrace(sb, innerCause.getStackTrace(), indent + 1); dumpInnerCauses(sb, innerCause.getCause(), indent); }
@NonNls private static String message(Throwable e) { String message = e.getMessage(); if (message != null) return message; message = e.getLocalizedMessage(); if (message != null) return message; message = e.toString(); Throwable cause = e.getCause(); if (cause != null) { String causeMessage = message(cause); return message + " (cause: " + causeMessage + ")"; } return message; }
public Object invokeMethod(Object object, String methodName, Object[] arguments) { try { return delegate.invokeMethod(object, methodName, arguments); } catch (MissingMethodException mme) { // attempt builder resolution try { if (builder.getMetaClass().respondsTo(builder, methodName).isEmpty()) { // dispatch to factories if it is not a literal method return builder.invokeMethod(methodName, arguments); } else { return InvokerHelper.invokeMethod(builder, methodName, arguments); } } catch (MissingMethodException mme2) { // chain secondary exception Throwable root = mme; while (root.getCause() != null) { root = root.getCause(); } root.initCause(mme2); // throw original throw mme; } } }
/** * Invokes the constructor belonging to the class named by {@code name} having the given parameter * types on the given arguments. Returns {@code null} if the class cannot be found, or the * constructor does not exist or cannot be invoked on the given arguments. * * @param <T> the type to which the constructor belongs * @param name the name of the class to which the constructor belongs * @param paramTypes the types of the constructor's parameters * @param args the arguments on which to invoke the constructor * @return the result of the constructor invocation on {@code args}, or null if the constructor * does not exist or could not be invoked */ @SuppressWarnings("unchecked") public static <T> T invokeConstructorFor(String name, Class<?>[] paramTypes, Object[] args) { // Load the class. Class<T> cls = null; try { cls = (Class<T>) Class.forName(name); } catch (Exception e) { // no class is found, simply return null return null; } assert cls != null : "reflectively loading " + name + " failed"; // Invoke the constructor. try { Constructor<T> ctor = cls.getConstructor(paramTypes); return ctor.newInstance(args); } catch (Throwable t) { if (t instanceof InvocationTargetException) { Throwable err = t.getCause(); String msg; if (err instanceof CheckerError) { msg = err.getMessage(); } else { msg = err.toString(); } SourceChecker.errorAbort( "InvocationTargetException when invoking constructor for class " + name + "; Underlying cause: " + msg, t); } else { SourceChecker.errorAbort( "Unexpected " + t.getClass().getSimpleName() + " for " + "class " + name + " when invoking the constructor; parameter types: " + Arrays.toString(paramTypes), // + " and args: " + Arrays.toString(args), t); } return null; // dead code } }
public static Throwable findBestCause(Throwable e) { Throwable best = e; Throwable cause = e; int it = 0; while ((cause = cause.getCause()) != null && it++ < 10) { if (cause instanceof ClassCastException) { best = cause; break; } if (cause instanceof SQLException) { best = cause; break; } } return best; }
/** * Processes cache query request. * * @param sndId Sender node id. * @param req Query request. */ @SuppressWarnings("unchecked") @Override void processQueryRequest(UUID sndId, GridCacheQueryRequest req) { if (req.cancel()) { cancelIds.add(new CancelMessageId(req.id(), sndId)); if (req.fields()) removeFieldsQueryResult(sndId, req.id()); else removeQueryResult(sndId, req.id()); } else { if (!cancelIds.contains(new CancelMessageId(req.id(), sndId))) { if (!F.eq(req.cacheName(), cctx.name())) { GridCacheQueryResponse res = new GridCacheQueryResponse( cctx.cacheId(), req.id(), new IgniteCheckedException( "Received request for incorrect cache [expected=" + cctx.name() + ", actual=" + req.cacheName())); sendQueryResponse(sndId, res, 0); } else { threads.put(req.id(), Thread.currentThread()); try { GridCacheQueryInfo info = distributedQueryInfo(sndId, req); if (info == null) return; if (req.fields()) runFieldsQuery(info); else runQuery(info); } catch (Throwable e) { U.error(log(), "Failed to run query.", e); sendQueryResponse( sndId, new GridCacheQueryResponse(cctx.cacheId(), req.id(), e.getCause()), 0); if (e instanceof Error) throw (Error) e; } finally { threads.remove(req.id()); } } } } }
public static String getNestedExceptionMessage(Throwable e) { String last_message = ""; while (e != null) { String this_message; if (e instanceof UnknownHostException) { this_message = "Unknown host " + e.getMessage(); } else if (e instanceof FileNotFoundException) { this_message = "File not found: " + e.getMessage(); } else { this_message = e.getMessage(); } // if no exception message then pick up class name. if we have a deliberate // zero length string then we assume that the exception can be ignored for // logging purposes as it is just delegating if (this_message == null) { this_message = e.getClass().getName(); int pos = this_message.lastIndexOf("."); this_message = this_message.substring(pos + 1).trim(); } if (this_message.length() > 0 && last_message.indexOf(this_message) == -1) { last_message += (last_message.length() == 0 ? "" : ", ") + this_message; } e = e.getCause(); } return (last_message); }
/** * If the causal chain has a sun.jvm.hotspot.runtime.VMVersionMismatchException, attempt to load * VirtualMachineImpl class for target VM version. */ protected static Class handleVMVersionMismatch(InvocationTargetException ite) { Throwable cause = ite.getCause(); if (DEBUG) { System.out.println("checking for version mismatch..."); } while (cause != null) { try { if (isVMVersionMismatch(cause)) { if (DEBUG) { System.out.println("Triggering cross VM version support..."); } return loadVirtualMachineImplClass(getVMVersion(cause)); } } catch (Exception exp) { if (DEBUG) { System.out.println("failed to load VirtualMachineImpl class"); exp.printStackTrace(); } return null; } cause = cause.getCause(); } return null; }
/** * Handle an exception in the servlet. * * <p>This routine should be called whenever an exception has surfaced to the top level of the * servlet. It should not be overridden unless Aura is entirely subsumed. Most special cases can * be handled by the Aura user by implementing {@link ExceptionAdapter ExceptionAdapter}. * * @param t the throwable to write out. * @param quickfix is this exception a valid quick-fix * @param context the aura context. * @param request the request. * @param response the response. * @param written true if we have started writing to the output stream. * @throws IOException if the output stream does. * @throws ServletException if send404 does (should not generally happen). */ @Override public void handleServletException( Throwable t, boolean quickfix, AuraContext context, HttpServletRequest request, HttpServletResponse response, boolean written) throws IOException { try { Throwable mappedEx = t; boolean map = !quickfix; Format format = context.getFormat(); // // This seems to fail, though the documentation implies that you can do // it. // // if (written && !response.isCommitted()) { // response.resetBuffer(); // written = false; // } if (!written) { // Should we only delete for JSON? setNoCache(response); } if (mappedEx instanceof IOException) { // // Just re-throw IOExceptions. // throw (IOException) mappedEx; } else if (mappedEx instanceof NoAccessException) { Throwable cause = mappedEx.getCause(); String denyMessage = mappedEx.getMessage(); map = false; if (cause != null) { // // Note that the exception handler can remap the cause here. // cause = exceptionAdapter.handleException(cause); denyMessage += ": cause = " + cause.getMessage(); } // // Is this correct?!?!?! // if (format != Format.JSON) { this.send404(request.getServletContext(), request, response); if (!isProductionMode(context.getMode())) { // Preserve new lines and tabs in the stacktrace since this is directly being written on // to the // page denyMessage = "<pre>" + AuraTextUtil.escapeForHTML(denyMessage) + "</pre>"; response.getWriter().println(denyMessage); } return; } } else if (mappedEx instanceof QuickFixException) { if (isProductionMode(context.getMode())) { // // In production environments, we want wrap the quick-fix. But be a little careful here. // We should never mark the top level as a quick-fix, because that means that we gack // on every mis-spelled app. In this case we simply send a 404 and bolt. // if (mappedEx instanceof DefinitionNotFoundException) { DefinitionNotFoundException dnfe = (DefinitionNotFoundException) mappedEx; if (dnfe.getDescriptor() != null && dnfe.getDescriptor().equals(context.getApplicationDescriptor())) { // We're in production and tried to hit an aura app that doesn't exist. // just show the standard 404 page. this.send404(request.getServletContext(), request, response); return; } } map = true; mappedEx = new AuraUnhandledException("404 Not Found (Application Error)", mappedEx); } } if (map) { mappedEx = exceptionAdapter.handleException(mappedEx); } PrintWriter out = response.getWriter(); // // If we have written out data, We are kinda toast in this case. // We really want to roll it all back, but we can't, so we opt // for the best we can do. For HTML we can do nothing at all. // if (format == Format.JSON) { if (!written) { out.write(CSRF_PROTECT); } // // If an exception happened while we were emitting JSON, we want the // client to ignore the now-corrupt data structure. 404s and 500s // cause the client to prepend /*, so we can effectively erase the // bad data by appending a */ here and then serializing the exception // info. // out.write("*/"); // // Unfortunately we can't do the following now. It might be possible // in some cases, but we don't want to go there unless we have to. // } if (format == Format.JS || format == Format.CSS) { // Make sure js and css doesn't get cached in browser, appcache, etc response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } if (format == Format.JSON || format == Format.HTML || format == Format.JS || format == Format.CSS) { // // We only write out exceptions for HTML or JSON. // Seems bogus, but here it is. // // Start out by cleaning out some settings to ensure we don't // check too many things, leading to a circular failure. Note // that this is still a bit dangerous, as we seem to have a lot // of magic in the serializer. // // Clear the InstanceStack before trying to serialize the exception since the Throwable has // likely // rendered the stack inaccurate, and may falsely trigger NoAccessExceptions. InstanceStack stack = this.contextService.getCurrentContext().getInstanceStack(); List<String> list = stack.getStackInfo(); for (int count = list.size(); count > 0; count--) { stack.popInstance(stack.peek()); } serializationService.write(mappedEx, null, out); if (format == Format.JSON) { out.write("/*ERROR*/"); } } } catch (IOException ioe) { throw ioe; } catch (Throwable death) { // // Catch any other exception and log it. This is actually kinda bad, because something has // gone horribly wrong. We should write out some sort of generic page other than a 404, // but at this point, it is unclear what we can do, as stuff is breaking right and left. // try { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); exceptionAdapter.handleException(death); if (!isProductionMode(context.getMode())) { response.getWriter().println(death.getMessage()); } } catch (IOException ioe) { throw ioe; } catch (Throwable doubleDeath) { // we are totally hosed. if (!isProductionMode(context.getMode())) { response.getWriter().println(doubleDeath.getMessage()); } } } finally { this.contextService.endContext(); } }