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.processor.interceptor;
018
019 import org.apache.camel.AsyncCallback;
020 import org.apache.camel.CamelException;
021 import org.apache.camel.Exchange;
022 import org.apache.camel.Processor;
023 import org.apache.camel.processor.DelegateAsyncProcessor;
024
025 public class HandleFaultInterceptor extends DelegateAsyncProcessor {
026
027 public HandleFaultInterceptor() {
028 }
029
030 public HandleFaultInterceptor(Processor processor) {
031 super(processor);
032 }
033
034 @Override
035 public String toString() {
036 return "HandleFaultInterceptor[" + processor + "]";
037 }
038
039 @Override
040 public boolean process(final Exchange exchange, final AsyncCallback callback) {
041 return getProcessor().process(exchange, new AsyncCallback() {
042 public void done(boolean doneSync) {
043 try {
044 // handle fault after we are done
045 handleFault(exchange);
046 } finally {
047 // and let the original callback know we are done as well
048 callback.done(doneSync);
049 }
050 }
051 });
052 }
053
054 /**
055 * Handles the fault message by converting it to an Exception
056 */
057 protected void handleFault(Exchange exchange) {
058 // Take the fault message out before we keep on going
059 if (exchange.hasOut() && exchange.getOut().isFault()) {
060 final Object faultBody = exchange.getOut().getBody();
061 if (faultBody != null && exchange.getException() == null) {
062 // remove fault as we are converting it to an exception
063 exchange.setOut(null);
064 if (faultBody instanceof Throwable) {
065 exchange.setException((Throwable) faultBody);
066 } else {
067 // wrap it in an exception
068 exchange.setException(new CamelException(faultBody.toString()));
069 }
070 }
071 }
072 }
073
074 }