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 */ 017 package org.apache.camel.impl; 018 019 import org.apache.camel.Consumer; 020 import org.apache.camel.Exchange; 021 import org.apache.camel.Processor; 022 import org.apache.camel.spi.ExceptionHandler; 023 024 /** 025 * An {@link ExceptionHandler} that uses the {@link DefaultConsumer} to 026 * process the caused exception to send the message into the Camel routing engine 027 * which allows to let the routing engine handle the exception. 028 * <p/> 029 * An endpoint can be configured with <tt>consumer.bridgeErrorHandler=true</tt> in the URI 030 * to enable this {@link BridgeExceptionHandlerToErrorHandler} on the consumer. 031 * The consumer must extend the {@link DefaultConsumer}, to support this, if not an 032 * {@link IllegalArgumentException} is thrown upon startup. 033 */ 034 public class BridgeExceptionHandlerToErrorHandler implements ExceptionHandler { 035 036 private final LoggingExceptionHandler fallback; 037 private final Consumer consumer; 038 private final Processor bridge; 039 040 public BridgeExceptionHandlerToErrorHandler(DefaultConsumer consumer) { 041 this.consumer = consumer; 042 this.fallback = new LoggingExceptionHandler(consumer.getClass()); 043 this.bridge = consumer.getProcessor(); 044 } 045 046 @Override 047 public void handleException(Throwable exception) { 048 handleException(null, exception); 049 } 050 051 @Override 052 public void handleException(String message, Throwable exception) { 053 handleException(message, null, exception); 054 } 055 056 @Override 057 public void handleException(String message, Exchange exchange, Throwable exception) { 058 if (exchange == null) { 059 exchange = consumer.getEndpoint().createExchange(); 060 } 061 062 // set the caused exception 063 exchange.setException(exception); 064 // and the message 065 exchange.getIn().setBody(message); 066 // and mark as redelivery exhausted as we cannot do redeliveries 067 exchange.setProperty(Exchange.REDELIVERY_EXHAUSTED, Boolean.TRUE); 068 069 try { 070 bridge.process(exchange); 071 } catch (Exception e) { 072 fallback.handleException("Error handling exception " + exception.getMessage(), exchange, e); 073 } 074 } 075 }