apache-camel

Add json-validator result to validated json object


I´m trying to validate an incoming json string against a json schema, but instead of throwing an exception if that validation fails, I´d like to forward the validation errors together with the validated json payload:

from("direct:myValidator")
.log("Validating json...")
.to("json-validator:myschema.json") 
.onException(org.apache.camel.component.jsonvalidator.JsonValidationException.class)
.continued(true)
.transform().???;

So ideally I would have a a json object like "validatedJson":*original json*, "validationResult":*excepted integer but got string*" after that. I understand that with simple and ${exception.message} I can access the errors. But I didn´t manage to turn that into valid json and combine it with the original message.


Solution

  • You need to process the message with a Processor to transform it accordingly. You can do something like this in your onException block:

    .process(exchange -> {
      String originalJson = exchange.getIn().getBody(String.class);
      JsonValidationException cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, JsonValidationException.class);
      String out = "{\"validatedJson\": \"" + originalJson + "\", \"validationResult\": \"" + cause.toString() + "\"}";
      exchange.getIn().setBody(out);
    })
    

    First you will read the body as the original json. You can also get the exception as you already know. And then you will create a new body, containing the original json and the error message. We're creating the json by hand, but of course, with more complex structure, you should use a library.