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