001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.processor;
018
019import java.util.List;
020
021import org.apache.camel.AsyncCallback;
022import org.apache.camel.Exchange;
023import org.apache.camel.Predicate;
024import org.apache.camel.Processor;
025import org.apache.camel.Traceable;
026import org.apache.camel.util.ExchangeHelper;
027import org.apache.camel.util.ObjectHelper;
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030
031/**
032 * A processor which catches exceptions.
033 *
034 * @version 
035 */
036public class CatchProcessor extends DelegateAsyncProcessor implements Traceable {
037    private static final Logger LOG = LoggerFactory.getLogger(CatchProcessor.class);
038
039    private final List<Class<? extends Throwable>> exceptions;
040    private final Predicate onWhen;
041    private final Predicate handled;
042
043    public CatchProcessor(List<Class<? extends Throwable>> exceptions, Processor processor, Predicate onWhen, Predicate handled) {
044        super(processor);
045        this.exceptions = exceptions;
046        this.onWhen = onWhen;
047        this.handled = handled;
048    }
049
050    @Override
051    public String toString() {
052        return "Catch[" + exceptions + " -> " + getProcessor() + "]";
053    }
054
055    public String getTraceLabel() {
056        return "catch";
057    }
058
059    @Override
060    public boolean process(final Exchange exchange, final AsyncCallback callback) {
061        Exception e = exchange.getException();
062        Throwable caught = catches(exchange, e);
063        // If a previous catch clause handled the exception or if this clause does not match, exit
064        if (exchange.getProperty(Exchange.EXCEPTION_HANDLED) != null || caught == null) {
065            callback.done(true);
066            return true;
067        }
068        if (LOG.isTraceEnabled()) {
069            LOG.trace("This CatchProcessor catches the exception: {} caused by: {}", caught.getClass().getName(), e.getMessage());
070        }
071
072        // store the last to endpoint as the failure endpoint
073        if (exchange.getProperty(Exchange.FAILURE_ENDPOINT) == null) {
074            exchange.setProperty(Exchange.FAILURE_ENDPOINT, exchange.getProperty(Exchange.TO_ENDPOINT));
075        }
076        // give the rest of the pipeline another chance
077        exchange.setProperty(Exchange.EXCEPTION_HANDLED, true);
078        exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e);
079        exchange.setException(null);
080        // and we should not be regarded as exhausted as we are in a try .. catch block
081        exchange.removeProperty(Exchange.REDELIVERY_EXHAUSTED);
082
083        // is the exception handled by the catch clause
084        final boolean handled = handles(exchange);
085
086        if (LOG.isDebugEnabled()) {
087            LOG.debug("The exception is handled: {} for the exception: {} caused by: {}",
088                    new Object[]{handled, e.getClass().getName(), e.getMessage()});
089        }
090
091        boolean sync = processor.process(exchange, new AsyncCallback() {
092            public void done(boolean doneSync) {
093                if (!handled) {
094                    if (exchange.getException() == null) {
095                        exchange.setException(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class));
096                    }
097                }
098                // always clear redelivery exhausted in a catch clause
099                exchange.removeProperty(Exchange.REDELIVERY_EXHAUSTED);
100
101                if (!doneSync) {
102                    // signal callback to continue routing async
103                    ExchangeHelper.prepareOutToIn(exchange);
104                }
105
106                callback.done(doneSync);
107            }
108        });
109
110        return sync;
111    }
112
113    /**
114     * Returns with the exception that is caught by this processor.
115     *
116     * This method traverses exception causes, so sometimes the exception
117     * returned from this method might be one of causes of the parameter
118     * passed.
119     *
120     * @param exchange  the current exchange
121     * @param exception the thrown exception
122     * @return Throwable that this processor catches. <tt>null</tt> if nothing matches.
123     */
124    protected Throwable catches(Exchange exchange, Throwable exception) {
125        // use the exception iterator to walk the caused by hierarchy
126        for (final Throwable e : ObjectHelper.createExceptionIterable(exception)) {
127            // see if we catch this type
128            for (final Class<?> type : exceptions) {
129                if (type.isInstance(e) && matchesWhen(exchange)) {
130                    return e;
131                }
132            }
133        }
134
135        // not found
136        return null;
137    }
138
139    /**
140     * Whether this catch processor handles the exception it have caught
141     *
142     * @param exchange  the current exchange
143     * @return <tt>true</tt> if this processor handles it, <tt>false</tt> otherwise.
144     */
145    protected boolean handles(Exchange exchange) {
146        if (handled == null) {
147            // handle by default
148            return true;
149        }
150
151        return handled.matches(exchange);
152    }
153
154    public List<Class<? extends Throwable>> getExceptions() {
155        return exceptions;
156    }
157
158    /**
159     * Strategy method for matching the exception type with the current exchange.
160     * <p/>
161     * This default implementation will match as:
162     * <ul>
163     *   <li>Always true if no when predicate on the exception type
164     *   <li>Otherwise the when predicate is matches against the current exchange
165     * </ul>
166     *
167     * @param exchange the current {@link org.apache.camel.Exchange}
168     * @return <tt>true</tt> if matched, <tt>false</tt> otherwise.
169     */
170    protected boolean matchesWhen(Exchange exchange) {
171        if (onWhen == null) {
172            // if no predicate then it's always a match
173            return true;
174        }
175        return onWhen.matches(exchange);
176    }
177}