用于架构验证错误的自定义映射器

时间:2015-06-25 13:27:36

标签: java xml validation xsd apache-camel

我已经使用了camel validator,并且我从模式验证中捕获了错误,如:

org.xml.sax.SAXParseException: cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type

是否有任何工具可以将这些错误映射到更漂亮的陈述?我总是可以迭代错误,拆分它们并准备自定义映射器,但也许有比这更好的东西? :)

3 个答案:

答案 0 :(得分:1)

Saxon非常擅长错误报告。它的验证器首先为您提供可理解的消息。

答案 1 :(得分:1)

这是一条SAX错误消息,看起来非常明确,但请参阅ErrorHandlerDefaultHandler来自定义它,不过您愿意。

答案 2 :(得分:1)

我已经通过camel验证组件使用xsd创建了验证:

<to uri="validator:xsd/myValidator.xsd"/>

然后我在doTry块中使用了doCatch来捕获异常:

<doCatch>
    <exception>org.apache.camel.ValidationException</exception>
    <log message="catch exception ${body}" loggingLevel="ERROR" />
    <process ref="schemaErrorHandler"/>
</doCatch>

之后我编写了自定义Camel处理器并且效果很好:)

    public class SchemaErrorHandler implements Processor {

    private final String STATUS_CODE = "6103";

    private final String SEVERITY_CODE = "2";

    @Override
    public void process(Exchange exchange) throws Exception {

        Map<String, Object> map = exchange.getProperties();
        String statusDesc = "Unknown exception";
        if (map != null) {
            SchemaValidationException exception = (SchemaValidationException) map.get("CamelExceptionCaught");
            if (exception != null && !CollectionUtils.isEmpty(exception.getErrors())) {
                StringBuffer buffer = new StringBuffer();
                for (SAXParseException e : exception.getErrors()) {
                    statusDesc = e.getMessage();
                    buffer.append(statusDesc);
                }
                statusDesc = buffer.toString();
            }
        }
        Fault fault = new Fault(new Message(statusDesc, (ResourceBundle) null));
        fault.setDetail(ErrorUtils.createDetailSection(STATUS_CODE, statusDesc, exchange, SEVERITY_CODE));
        throw fault;
    }
}