I am new to Apache Camel. My requirement is that, whenever a custom exception occur, i want to set a custom Body and response code and send it back to the user as response. I have used OnException Block to catch the custom exception :
onException(CustomException.class)
.handled(true)
.to("direct:customErrorHandler");
My customErrorHandler is a route in a different class "CustomErrorhandler":-
@Component
public class CustomExceptionHandler extends RouteBuilder {
@Autowired
private CommonExceptionProcessor commonExceptionProcessor;
@Override
public void configure() throws Exception {
JacksonDataFormat jackErrorResponse = new JacksonDataFormat(jacksonConfig.jsonObjectMapper(), Error.class);
from("direct:customErrorHandler")
.routeId("customErrorHandler-Route")
.log(LoggingLevel.DEBUG, this.getClass().getName(), "Handling Error")
.process(commonExceptionProcessor)
.marshal(jackErrorResponse)
}
}
My Common expection processor:-
@Component
public class CommonExceptionProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
CustomException ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, CustomException.class);
Error e = new Error();
e.setMessage(ex.getMessage());
e.setStatus("FAILED");
exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, ex.getCode());
exchange.getIn().setBody(e,Error.class);
}
}
But whenever this exception is occuring, i am getting empty response with garbage statusCode. please help.
Expectated Response:
{
"message":"customException occured",
"status":"FAILED"
}