如何为jsonschema定制错误消息?

jfgube3f  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(475)

有没有办法根据给定的条件提供自定义错误消息?我在用https://github.com/networknt/json-schema-validator,版本1.0.43
这是我的json模式:

{
  "$id": "https://configurations/provider.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Configuration",
  "type": "object",
  "properties": {
    "provider": {
      "description": "Name of the provider.",
      "enum": [
        "Provider #1",
        "Provider #2"
      ]
    },
    "configuration": {
      "$schema": "json-schema/configurations/configuration.json"
    }
  },
  "if": {
    "properties": {
      "parcsProvider": {
        "const": "Provider #1"
      }
    }
  },
  "then": {
    "required": [
      "configuration"
    ]
  },
  "else": {
    "not": {
      "required": [
        "configuration"
      ]
    }
  }
}

如果提供程序的值是“provider#1”,则需要配置对象,如果是“provider#2”,并且传递了配置,则会发生错误。我想自定义该错误,使响应与现在相同,但带有类似“provider 2 cannot have a configuration”的自定义消息
当前错误消息/响应:

{
    "timestamp": "2020-11-23T12:50:56.20658+01:00",
    "message": "invalid.json.input",
    "validationErrors": [
        {
            "field": "$",
            "message": "$: should not be valid to the schema \"not\" : {\"required\":[\"configuration\"]}"
        }
    ]
}
3b6akqbq

3b6akqbq1#

我在我的一个项目中也有类似的要求。为了验证,我用了https://github.com/everit-org/json-schema.
我就是这么做的
分类了验证程序抛出的所有类型的错误[必须有一些特定的关键字]
现在,一旦拥有了所有键,就可以轻松地处理错误并发送自定义错误/响应。
下面是我收集的不同案件的关键,这可能会帮助你-

MIN_LENGTH_VIOLATION = "expected minLength"
MAX_LENGTH_VIOLATION = "expected maxLength"
PATTERN_VIOLATION = "does not match pattern"
DATA_TYPE_VIOLATION = "expected type"
DEPENDENCY_VIOLATION = "is required"
FORMAT_VIOLATION_OR_ENUM_VALIDATION_VIOLATION = "is not a valid"
MANDATORY_FIELD_VIOLATION_OR_CONDITIONAL_VIOLATION = "required key"
NUMBER_IS_LESS_THAN_VIOLATION = "is not greater or equal to"
NUMBER_IS_GREATER_THAN_VIOLATION = "is not less or equal"
EXCLUSIVE_NUMBER_IS_GREATER_THAN_VIOLATION = "is not less than"
EXCLUSIVE_NUMBER_IS_LESS_THAN_VIOLATION = "is not greater than"
MULTIPLE_OF_VIOLATION = "is not a multiple"

样本代码-

private static void validate(JSONObject request) {
    try {
        // Schema, that might be fetched dynamically from some data source
        JSONObject schema = new JSONObject();
        Schema loadedSchema = SchemaLoader.load(schema);
        loadedSchema.validate(request);
    } catch (ValidationException ve) {
        List<String> allErrorMessages = ve.getAllMessages();
        List<String> mandatoryFields = parseMandatoryField(allErrorMessages);
        if (CollectionUtils.isNotEmpty(mandatoryFields)) {
            throw new MandFieldMissingExp(mandatoryFields);
        } else {
            List<String> invalidFields = parseInvalids(allErrorMessages);
            throw new InvalidFieldExp(invalidFields);
        }
    }
}

private static List<String> parseMandatoryField(List<String> validationExceptionMessages) {
    Set<String> mandatoryListSet = new HashSet<>();
    validationExceptionMessages.forEach(errorMessage -> {
        if (StringUtils.containsAny(errorMessage, MANDATORY_FIELD_VIOLATION_OR_CONDITIONAL_VIOLATION, DEPENDENCY_VIOLATION)) {
            mandatoryListSet.add(StringUtils.substring(errorMessage, errorMessage.indexOf('[') + 1, errorMessage.indexOf(']')));
        }
    });
    return new ArrayList<>(mandatoryListSet);
}

private static List<String> parseInvalids(List<String> validationExceptionMessages) {
    Set<String> invalidParamsSet = new HashSet<>();
    validationExceptionMessages.forEach(errorMessage -> {
        if (StringUtils.containsAny(errorMessage, MIN_LENGTH_VIOLATION, MAX_LENGTH_VIOLATION, PATTERN_VIOLATION,
                FORMAT_VIOLATION_OR_ENUM_VALIDATION_VIOLATION, DATA_TYPE_VIOLATION, NUMBER_IS_LESS_THAN_VIOLATION,
                MULTIPLE_OF_VIOLATION, EXCLUSIVE_NUMBER_IS_GREATER_THAN_VIOLATION, NUMBER_IS_GREATER_THAN_VIOLATION
                , EXCLUSIVE_NUMBER_IS_LESS_THAN_VIOLATION)) {
            invalidParamsSet.add(StringUtils.substring(errorMessage, errorMessage.indexOf('/') + 1, errorMessage.indexOf(':')));
        }
    });
    return new ArrayList<>(invalidParamsSet);
}

希望有帮助

相关问题