如何将传入请求的字段名称绑定到适当的错误消息,格式如下。 field1
应该引用@JsonProperty("field1")
的内容,而是绑定到具有以下格式的路径Resource.method.arg0.field1
预期产出
{
"errors": [
{
"field": "field1",
"message": "error message"
}
]
}
我有以下ConstraintExceptionMapper,但这看起来是错误的方法。是否有任何合适的替代方法允许我继续使用javax验证,但将@QueryParam("productCode")
的值绑定到自定义错误对象。
public class CustomConstraintViolationExceptionMapper implements ExceptionMapper<JerseyViolationException> {
@Override
public Response toResponse(JerseyViolationException exception) {
List<ValidationError> validationErrors = constraintViolationToValidationErrors(exception);
final Invocable invocable = exception.getInvocable();
final int status = determineStatus(exception.getConstraintViolations(), invocable);
List<Error> errors =
validationErrors.stream()
.map((e) -> new Error(e.getPath(), e.getMessage()))
.collect(Collectors.toList());
return Response.status(status).entity(new Errors(errors)).build();
}
private String getFieldName(String path) {
return path.substring(path.lastIndexOf(".") + 1, path.length());
}
}
请求对象
public class RequestObject {
@JsonProperty
@NotEmpty(message = "field1 is a required parameter")
private final String field1;
@JsonCreator
public FutureTradeDateParams(@QueryParam("field1") String field1) {
this.field1 = field1;
}
@JsonProperty("field1")
public String getField1() {
return field1;
}
}