Spring Data Rest中手动验证的响应错误格式



当使用Spring Data REST和JSR 303 Bean Validation时,当存在约束冲突时,我会得到如下响应:

{
"errors": [
{
"entity": "Empresa",
"property": "observacao",
"invalidValue": "",
"message": "O tamanho do campo deve ser entre 1 e 255"
}
]
}

但是我正在尝试手动验证一个对象,并且我希望以Spring Data Rest使用的相同格式返回验证错误

@DeleteMapping("/departamento/{id}")
public @ResponseBody
ResponseEntity<?> filtro(@PathVariable Long id){
Optional<Departamento> departamentoOpt = this.departamentoRepository.findById(id);
if (!departamentoOpt.isPresent()) {
return ResponseEntity.notFound().build();
}
Departamento departamento = departamentoOpt.get();
BindingResult errors = new BeanPropertyBindingResult(
departamento, "departamento");
this.validator.validate(departamento, errors, PreDeleteValidation.class);
if (errors.hasErrors()) {
// How to return a response in the same format used by SDR here?
}
return ResponseEntity.ok().build();
}

如何才能做到这一点?

您可以在验证失败时抛出和Exception,并注册一个Spring MVC Controller Advice来捕获它并将其转换为满足您需求的东西。

if (errors.hasErrors()) {
throw new org.springframework.web.bind.MethodArgumentNotValidException(
departamento, bindingResult)
}

建议可能如下所示:

@ControllerAdvice
public class ErrorHandlingAdvice
{
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationError processValidationError(MethodArgumentNotValidException ex)
{
ValidationError error = new ValidationError();
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors)
{
error.addError(fieldError.getField(), fieldError.getDefaultMessage());
}
return error;
}
}

ValidationError只是一个简单的bean:

public class ValidationError
{
private final Map<String, List<String>> errors;
public ValidationError()
{
errors = new TreeMap<>();
}
public void addError(String field, String error)
{
if (!errors.containsKey(field))
{
errors.put(field, new ArrayList<String>());
}
errors.get(field).add(error);
}
public Map<String, List<String>> getErrors()
{
return errors;
}
}

相关内容

  • 没有找到相关文章

最新更新