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

时间:2018-12-03 18:54:10

标签: spring spring-data-rest

当使用Spring Data RESTJSR 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();

  }

这怎么实现?

1 个答案:

答案 0 :(得分:1)

您可以在验证失败时抛出Exception并注册一个Spring MVC Controller建议以捕获该错误并将其转换为满足您需求的内容。

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.gradle:osdetector-gradle-plugin:1.6.0'
    }
}

plugins {
    id 'java'
}

apply plugin: 'com.google.osdetector'

ext.platform = osdetector.os == 'osx' ? 'mac' : osdetector.os == 'windows' ? 'win' : osdetector.os

version = '0.1.0'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.openjfx:javafx-graphics:11:$platform"
}

建议可能如下所示:

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

ValidationError只是一个简单的bean:

@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;
  }
}