模式验证错误的自定义映射器

Custom mapper for schema validation errors

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

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

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

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

那是一条 SAX 错误消息,它似乎表述得很清楚,但请参阅 ErrorHandler and DefaultHandler 以根据您的喜好对其进行自定义。

我已经通过骆驼验证组件使用 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;
    }
}