Search in sources :

Example 11 with OnExceptionDefinition

use of org.apache.camel.model.OnExceptionDefinition in project camel by apache.

the class DefaultExceptionPolicyStrategyTest method testCausedByWrapped.

public void testCausedByWrapped() {
    setupPoliciesCausedBy();
    IOException ioe = new IOException("Damm");
    ioe.initCause(new FileNotFoundException("Somefile not found"));
    OnExceptionDefinition result = strategy.getExceptionPolicy(policies, null, new RuntimeCamelException(ioe));
    assertEquals(type1, result);
}
Also used : FileNotFoundException(java.io.FileNotFoundException) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException)

Example 12 with OnExceptionDefinition

use of org.apache.camel.model.OnExceptionDefinition in project camel by apache.

the class DefaultExceptionPolicyStrategyTest method testCausedByOtherIO.

public void testCausedByOtherIO() {
    setupPoliciesCausedBy();
    IOException ioe = new IOException("Damm");
    ioe.initCause(new MalformedURLException("Bad url"));
    OnExceptionDefinition result = strategy.getExceptionPolicy(policies, null, ioe);
    assertEquals(type2, result);
}
Also used : MalformedURLException(java.net.MalformedURLException) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition) IOException(java.io.IOException)

Example 13 with OnExceptionDefinition

use of org.apache.camel.model.OnExceptionDefinition in project camel by apache.

the class DefaultExceptionPolicyStrategy method findMatchedExceptionPolicy.

private boolean findMatchedExceptionPolicy(Map<ExceptionPolicyKey, OnExceptionDefinition> exceptionPolicies, Exchange exchange, Throwable exception, Map<Integer, OnExceptionDefinition> candidates) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Finding best suited exception policy for thrown exception {}", exception.getClass().getName());
    }
    // the goal is to find the exception with the same/closet inheritance level as the target exception being thrown
    int targetLevel = getInheritanceLevel(exception.getClass());
    // candidate is the best candidate found so far to return
    OnExceptionDefinition candidate = null;
    // difference in inheritance level between the current candidate and the thrown exception (target level)
    int candidateDiff = Integer.MAX_VALUE;
    // loop through all the entries and find the best candidates to use
    Set<Map.Entry<ExceptionPolicyKey, OnExceptionDefinition>> entries = exceptionPolicies.entrySet();
    for (Map.Entry<ExceptionPolicyKey, OnExceptionDefinition> entry : entries) {
        Class<?> clazz = entry.getKey().getExceptionClass();
        OnExceptionDefinition type = entry.getValue();
        // so we will not pick an OnException from another route
        if (exchange != null && exchange.getUnitOfWork() != null && type.isRouteScoped()) {
            RouteDefinition route = exchange.getUnitOfWork().getRouteContext() != null ? exchange.getUnitOfWork().getRouteContext().getRoute() : null;
            RouteDefinition typeRoute = ProcessorDefinitionHelper.getRoute(type);
            if (route != null && typeRoute != null && route != typeRoute) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("The type is scoped for route: {} however Exchange is at route: {}", typeRoute.getId(), route.getId());
                }
                continue;
            }
        }
        if (filter(type, clazz, exception)) {
            // must match
            if (!matchesWhen(type, exchange)) {
                LOG.trace("The type did not match when: {}", type);
                continue;
            }
            // exact match then break
            if (clazz.equals(exception.getClass())) {
                candidate = type;
                candidateDiff = 0;
                break;
            }
            // not an exact match so find the best candidate
            int level = getInheritanceLevel(clazz);
            int diff = targetLevel - level;
            if (diff < candidateDiff) {
                // replace with a much better candidate
                candidate = type;
                candidateDiff = diff;
            }
        }
    }
    if (candidate != null) {
        if (!candidates.containsKey(candidateDiff)) {
            // only add as candidate if we do not already have it registered with that level
            LOG.trace("Adding {} as candidate at level {}", candidate, candidateDiff);
            candidates.put(candidateDiff, candidate);
        } else {
            // for example we check route scope before context scope (preferring route scopes)
            if (LOG.isTraceEnabled()) {
                LOG.trace("Existing candidate {} takes precedence over{} at level {}", new Object[] { candidates.get(candidateDiff), candidate, candidateDiff });
            }
        }
    }
    // if we found a exact match then we should stop continue looking
    boolean exactMatch = candidateDiff == 0;
    if (LOG.isTraceEnabled() && exactMatch) {
        LOG.trace("Exact match found for candidate: {}", candidate);
    }
    return exactMatch;
}
Also used : RouteDefinition(org.apache.camel.model.RouteDefinition) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 14 with OnExceptionDefinition

use of org.apache.camel.model.OnExceptionDefinition in project camel by apache.

the class TraceInterceptor method process.

@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // do not trace if tracing is disabled
    if (!tracer.isEnabled() || (routeContext != null && !routeContext.isTracing())) {
        return processor.process(exchange, callback);
    }
    // logging TraceEvents to avoid infinite looping
    if (exchange.getProperty(Exchange.TRACE_EVENT, false, Boolean.class)) {
        // but we must still process to allow routing of TraceEvents to eg a JPA endpoint
        return processor.process(exchange, callback);
    }
    final boolean shouldLog = shouldLogNode(node) && shouldLogExchange(exchange);
    // whether we should trace it or not, some nodes should be skipped as they are abstract
    // intermediate steps for instance related to on completion
    boolean trace = true;
    boolean sync = true;
    // okay this is a regular exchange being routed we might need to log and trace
    try {
        // before
        if (shouldLog) {
            // traced holds the information about the current traced route path
            if (exchange.getUnitOfWork() != null) {
                TracedRouteNodes traced = exchange.getUnitOfWork().getTracedRouteNodes();
                if (node instanceof OnCompletionDefinition || node instanceof OnExceptionDefinition) {
                    // skip any of these as its just a marker definition
                    trace = false;
                } else if (ProcessorDefinitionHelper.isFirstChildOfType(OnCompletionDefinition.class, node)) {
                    // special for on completion tracing
                    traceOnCompletion(traced, exchange);
                } else if (ProcessorDefinitionHelper.isFirstChildOfType(OnExceptionDefinition.class, node)) {
                    // special for on exception
                    traceOnException(traced, exchange);
                } else if (ProcessorDefinitionHelper.isFirstChildOfType(CatchDefinition.class, node)) {
                    // special for do catch
                    traceDoCatch(traced, exchange);
                } else if (ProcessorDefinitionHelper.isFirstChildOfType(FinallyDefinition.class, node)) {
                    // special for do finally
                    traceDoFinally(traced, exchange);
                } else if (ProcessorDefinitionHelper.isFirstChildOfType(AggregateDefinition.class, node)) {
                    // special for aggregate
                    traceAggregate(traced, exchange);
                } else {
                    // regular so just add it
                    traced.addTraced(new DefaultRouteNode(node, super.getProcessor()));
                }
            } else {
                LOG.trace("Cannot trace as this Exchange does not have an UnitOfWork: {}", exchange);
            }
        }
        // log and trace the processor
        Object state = null;
        if (shouldLog && trace) {
            logExchange(exchange);
            // either call the in or generic trace method depending on OUT has been enabled or not
            if (tracer.isTraceOutExchanges()) {
                state = traceExchangeIn(exchange);
            } else {
                traceExchange(exchange);
            }
        }
        final Object traceState = state;
        // special for interceptor where we need to keep booking how far we have routed in the intercepted processors
        if (node.getParent() instanceof InterceptDefinition && exchange.getUnitOfWork() != null) {
            TracedRouteNodes traced = exchange.getUnitOfWork().getTracedRouteNodes();
            traceIntercept((InterceptDefinition) node.getParent(), traced, exchange);
        }
        // process the exchange
        sync = processor.process(exchange, new AsyncCallback() {

            @Override
            public void done(boolean doneSync) {
                try {
                    // after (trace out)
                    if (shouldLog && tracer.isTraceOutExchanges()) {
                        logExchange(exchange);
                        traceExchangeOut(exchange, traceState);
                    }
                } catch (Throwable e) {
                    // some exception occurred in trace logic
                    if (shouldLogException(exchange)) {
                        logException(exchange, e);
                    }
                    exchange.setException(e);
                } finally {
                    // ensure callback is always invoked
                    callback.done(doneSync);
                }
            }
        });
    } catch (Throwable e) {
        // some exception occurred in trace logic
        if (shouldLogException(exchange)) {
            logException(exchange, e);
        }
        exchange.setException(e);
    }
    return sync;
}
Also used : CatchDefinition(org.apache.camel.model.CatchDefinition) AsyncCallback(org.apache.camel.AsyncCallback) OnCompletionDefinition(org.apache.camel.model.OnCompletionDefinition) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition) AggregateDefinition(org.apache.camel.model.AggregateDefinition) TracedRouteNodes(org.apache.camel.spi.TracedRouteNodes) DefaultRouteNode(org.apache.camel.impl.DefaultRouteNode) InterceptDefinition(org.apache.camel.model.InterceptDefinition)

Example 15 with OnExceptionDefinition

use of org.apache.camel.model.OnExceptionDefinition in project camel by apache.

the class ErrorHandlerSupportTest method testOnePolicyChildFirst.

public void testOnePolicyChildFirst() {
    List<Class<? extends Throwable>> exceptions = new ArrayList<Class<? extends Throwable>>();
    exceptions.add(ChildException.class);
    exceptions.add(ParentException.class);
    ErrorHandlerSupport support = new ShuntErrorHandlerSupport();
    support.addExceptionPolicy(null, new OnExceptionDefinition(exceptions));
    assertEquals(ChildException.class, getExceptionPolicyFor(support, new ChildException(), 0));
    assertEquals(ParentException.class, getExceptionPolicyFor(support, new ParentException(), 1));
}
Also used : ArrayList(java.util.ArrayList) OnExceptionDefinition(org.apache.camel.model.OnExceptionDefinition)

Aggregations

OnExceptionDefinition (org.apache.camel.model.OnExceptionDefinition)24 IOException (java.io.IOException)9 FileNotFoundException (java.io.FileNotFoundException)6 ConnectException (java.net.ConnectException)5 AlreadyStoppedException (org.apache.camel.AlreadyStoppedException)4 CamelExchangeException (org.apache.camel.CamelExchangeException)4 MalformedURLException (java.net.MalformedURLException)3 SocketException (java.net.SocketException)3 ExchangeTimedOutException (org.apache.camel.ExchangeTimedOutException)3 RuntimeCamelException (org.apache.camel.RuntimeCamelException)3 ValidationException (org.apache.camel.ValidationException)3 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 AsyncCallback (org.apache.camel.AsyncCallback)1 AsyncProcessor (org.apache.camel.AsyncProcessor)1 Processor (org.apache.camel.Processor)1 DefaultRouteNode (org.apache.camel.impl.DefaultRouteNode)1