Resolves a fallback for the given execution context and exception.

@param context   The context
@param exception The exception
@return Returns the fallback value or throws the original exception
183329
protected Object resolveFallback(MethodInvocationContext<Object, Object> context, RuntimeException exception) {
        if (exception instanceof NoAvailableServiceException) {
            NoAvailableServiceException nase = (NoAvailableServiceException) exception;
            if (LOG.isErrorEnabled()) {
                LOG.debug(nase.getMessage(), nase);
                LOG.error("Type [{}] attempting to resolve fallback for unavailable service [{}]", context.getTarget().getClass().getName(), nase.getServiceID());
            }
        } else {
            if (LOG.isErrorEnabled()) {
                LOG.error("Type [" + context.getTarget().getClass().getName() + "] executed with error: " + exception.getMessage(), exception);
            }
        }

        Optional<? extends MethodExecutionHandle<?, Object>> fallback = findFallbackMethod(context);
        if (fallback.isPresent()) {
            MethodExecutionHandle<?, Object> fallbackMethod = fallback.get();
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass().getName(), fallbackMethod);
                }
                return fallbackMethod.invoke(context.getParameterValues());
            } catch (Exception e) {
                throw new FallbackException("Error invoking fallback for type [" + context.getTarget().getClass().getName() + "]: " + e.getMessage(), e);
            }
        } else {
            throw exception;
        }
    }
298318
private ControllerErrorHandler getContextErrorHandler(XmlWebApplicationContext context) {
        ControllerErrorHandler errorHandler = null;
        String[] names = context.getBeanNamesForType(ControllerErrorHandler.class);
        for (int i = 0; errorHandler == null && i < names.length; i++) {
            errorHandler = (ControllerErrorHandler) context.getBean(names[i]);
            Class<?> userClass = ClassUtils.getUserClass(errorHandler);
            if (userClass.isAnnotationPresent(Ignored.class)) {
                logger.debug("Ignored controllerErrorHandler: " + errorHandler);
                errorHandler = null;
                continue;
            }
        }
        return errorHandler;
    }
25100
@Pure
	public static Object getContext() throws AndroidException {
		final Object ctx;
		synchronized (Android.class) {
			if (context == null) {
				throw new AndroidException();
			}
			ctx = context.get();
		}
		if (ctx == null) {
			throw new AndroidException();
		}
		return ctx;
	}
276228
public synchronized EvaluatorContext getContext(final String contextId) {
    for (final EvaluatorContext context : this.contextStack) {
      if (context.getId().equals(contextId)) {
        return context;
      }
    }
    throw new RuntimeException("Unknown evaluator context " + contextId);
  }
850023
@SuppressWarnings("unchecked")
    protected @Nullable Object doResolve(
            ArgumentConversionContext<T> context,
            ConvertibleValues<?> values,
            String annotationValue) {

        Object value = resolveValue(context, values, annotationValue);
        if (value == null) {
            String fallbackName = getFallbackFormat(context.getArgument());
            if (!annotationValue.equals(fallbackName)) {
                annotationValue = fallbackName;
                value = resolveValue(context, values, annotationValue);
            }
        }

        return value;
    }
906400
private RuntimeException unpackExecutionException(Throwable exc) {
    while (exc instanceof ExecutionException || exc instanceof UncheckedExecutionException) {
      exc = exc.getCause();
    }
    return Throwables.propagate(exc);
  }
814963
private static Throwable getWorkflowCause( Exception exception ){
        Throwable e = exception;
        while( e instanceof WorkflowException ){
            e = e.getCause();
        }
        return e;
    }
261027
public ApplicationContext getApplicationContext(final JobExecutionContext context) throws JobExecutionException {
        SchedulerContext schedulerContext;
        try {
            final Scheduler scheduler = context.getScheduler();
            schedulerContext = scheduler.getContext();
        } catch (SchedulerException e) {
        	logger.error("Unable to retrieve the scheduler context, cause : ", e);
            throw new JobExecutionException(e);
        }
        final ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_BEAN_NAME);
        return applicationContext;
    }
48597
public void         takeException(Exception exception) throws Exception
    {
        Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");

        boolean     passUp = true;
        if ( sessionHasFailed.get() )
        {
            switch ( mode )
            {
                case RETRY:
                {
                    sessionHasFailed.set(false);
                    failedSessionThreads.remove(ourThread);
                    if ( exception instanceof SessionFailedException )
                    {
                        isDone.set(false);
                        passUp = false;
                    }
                    break;
                }

                case FAIL:
                {
                    break;
                }
            }
        }

        if ( passUp )
        {
            retryLoop.takeException(exception);
        }
    }
240779
public ExceptionThrownRule getExceptionThrownRule(Throwable ex) {
        ExceptionThrownRule exceptionThrownRule = null;
        int deepest = Integer.MAX_VALUE;
        for (Map.Entry<String, ExceptionThrownRule> entry : exceptionThrownRuleMap.entrySet()) {
            int depth = getMatchedDepth(entry.getKey(), ex);
            if (depth >= 0 && depth < deepest) {
                deepest = depth;
                exceptionThrownRule = entry.getValue();
            }
        }
        return (exceptionThrownRule != null ? exceptionThrownRule : defaultExceptionThrownRule);
    }
894764
@Override
	protected void handleException(final SqlContext sqlContext, final SQLException ex) throws SQLException {
		SQLException cause = ex;

		while (cause.getNextException() != null) {
			cause = cause.getNextException();
		}

		if (LOG.isErrorEnabled() && isOutputExceptionLog()) {
			StringBuilder builder = new StringBuilder();
			builder.append(System.lineSeparator()).append("Exception occurred in SQL execution.")
					.append(System.lineSeparator());
			builder.append("Executed SQL[").append(sqlContext.getExecutableSql()).append("]")
					.append(System.lineSeparator());
			if (sqlContext instanceof SqlContextImpl) {
				Parameter[] bindParameters = ((SqlContextImpl) sqlContext).getBindParameters();
				for (int i = 0; i < bindParameters.length; i++) {
					Parameter parameter = getSqlFilterManager().doParameter(bindParameters[i]);
					builder.append("Bind Parameter.[INDEX[").append(i + 1).append("], ").append(parameter.toString())
							.append("]").append(System.lineSeparator());
				}
			}
			LOG.error(builder.toString(), cause);
		}

		throw cause;
	}
967427
public static <V> Predicate<TaskContext<V>> ifException(Predicate<? super Exception> predicate) {
        return ctx -> predicate.test(ctx.getException());
    }
372795
public Exception getRootCause() {
		if (exception instanceof ServiceLocatorException) {
			return ((ServiceLocatorException) exception).getRootCause();
		}
		return exception == null ? this : exception;
	}
1269880
public void onExceptionWithServer(ExecutionContext<I> context, Throwable exception, ExecutionInfo info) {
        for (ExecutionListener<I, O> listener: listeners) {
            try {
                if (!isListenerDisabled(listener)) {
                    listener.onExceptionWithServer(context.getChildContext(listener), exception, info);
                }
            } catch (Throwable e) {
                logger.error("Error invoking listener " + listener, e);
            }
        }
    }
70442
static DnsException translateAndThrow(RetryHelperException ex) {
    BaseServiceException.translate(ex);
    throw new DnsException(UNKNOWN_CODE, ex.getMessage(), ex.getCause());
  }
1284718
static int getBackoff(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
    }
248262
public Resolution intercept(ExecutionContext executionContext) throws Exception {
        // Remove expired contexts.
        removeExpired(contexts);
        
        // Get wait context, if any.
        Context context = getContext(executionContext);
        LifecycleStage stage = executionContext.getLifecycleStage();
        
        if (executionContext.getActionBeanContext().getRequest().getRequestURI().contains(THREAD_URL)) {
            // The request we are processing is the one used to invoke event handler in background and to get resolution to send to user when event completes.
            // Since we are going to invoke the real event, the action bean and event must stay the same.
            // Binding and validation must be skipped since they were done in the first request.
            switch (executionContext.getLifecycleStage()) {
                // Use action bean that will process event.
                case ActionBeanResolution:
                    log.trace("injecting ActionBean");
                    // Since session can be lost from original request (Tomcat is a good example), request must be updated with the background request.
                    context.actionBean.setContext(executionContext.getActionBeanContext());
                    executionContext.setActionBean(context.actionBean);
                    // Skip normal action bean resolution.
                    return null;
                // Select event to call.
                case HandlerResolution:
                    log.trace("injecting event handler");
                    executionContext.setHandler(context.eventHandler);
                    // Skip normal handler resolution.
                    return null;
                // No biding or validation, it was done before a background request was created to handle event.
                case BindingAndValidation:
                case CustomValidation:
                    log.trace("skipping binding and validation");
                    // Skip binding and validation.
                    return null;
                // Execute event since we are in the background request.
                case EventHandling:
                    log.trace("executing event handler");
                    // Execute event and save exception if any.
                    try {
                        return executionContext.proceed();
                    }
                    catch (Exception e) {
                        synchronized(context.actionBean)
                        {
                            log.trace("setting exception in context");
                            context.throwable = e;
                            context.status = Context.Status.COMPLETE;
                            context.completeMoment = System.currentTimeMillis();
                            context.actionBean.notifyAll();
                            context.eventFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
                        }
                        throw e;
                    }
                // Save resolution to send to user when he will refresh wait page.
                case ResolutionExecution:
                    synchronized(context.actionBean)
                    {
                        log.trace("setting resolution in context");
                        context.resolution = executionContext.getResolution();
                        context.status = Context.Status.COMPLETE;
                        context.completeMoment = System.currentTimeMillis();
                        context.actionBean.notifyAll();
                        context.eventFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
                    }
                    
                    // Use a default resolution to prevent processing the one event returned.
                    executionContext.setResolution(new StreamingResolution("text/plain", "thread complete"));
                    return executionContext.proceed();
                case RequestInit:
                case RequestComplete:
                    return executionContext.proceed();
            }
        }
        else {
            if (LifecycleStage.ActionBeanResolution.equals(stage)) {
                if (context != null) {
                    // We are using a wait context for this request. Go to wait page or event's resolution depending on status and skip everything else.
                    return checkStatus(executionContext, context);
                }
            }
            else if (LifecycleStage.EventHandling.equals(stage)) {
                WaitPage annotation = executionContext.getHandler().getAnnotation(WaitPage.class);
                if (annotation != null) {
                    // Event has @WaitPage annotation. Create wait context to invoke event in background and redirect user to wait page.
                    return createContextAndRedirect(executionContext, annotation);
                }
            }
        }
        
        return executionContext.proceed();
    }