从默认错误列表中删除对象Spring Boot验证

时间:2018-08-01 13:44:55

标签: spring spring-boot spring-validator

我正在Web服务中开发Spring Boot项目及其RestController和

@ResponseBody CustomResponse method(final @PathVariable("tag") String tag, @Valid @RequestBody Payload payload, HttpServletResponse httpServletResponse) { }

如果signatureHeight为Null,并且在有效载荷类中,signHeight由@NotNull批注

{
  "timestamp": "2018-08-01T13:30:41.859+0000",
  "status": 400,
  "error": "Bad Request",
  "errors": [
    {
      "codes": [
        "Positive.Payload.signatureHeight",
        "Positive.signatureHeight",
        "Positive.int",
        "Positive"
      ],
      "arguments": [
        {
          "codes": [
            "Payload.signatureHeight",
            "signatureHeight"
          ],
          "arguments": null,
          "defaultMessage": "signatureHeight",
          "code": "signatureHeight"
        }
      ],
      "defaultMessage": "must be greater than 0",
      "objectName": "Payload",
      "field": "signatureHeight",
      "rejectedValue": 0,
      "bindingFailure": false,
      "code": "Positive"
    }
  ],
  "message": "Validation failed for object='Payload'. Error count: 10",
  "path": "/e-sign/sign-pdf/XML"
}

我想从将在错误JsonArray中出现的每个对象中删除errors.codeserrors.arguments

这是否可以轻松实现而无需实现自己的自定义错误对象。

2 个答案:

答案 0 :(得分:0)

基本上可以。 但是您需要实现exception handling.

根据您的情况,最常见的解决方案是-在控制器内部声明下一个代码:

@ExceptionHandler({ConstraintViolationException.class, MethodArgumentNotValidException.class})
@ResponseBody
public ReturnType handleValidationException() {
    return ReturnType.somePreparedMessage();
}

答案 1 :(得分:0)

您可以使用GlobalExceptionalHandler。在这里,您可以处理所有类型的异常,并根据需要返回响应&& http状态代码。 这是方法参数无效的异常句柄的示例。您可以使用@ExceptionHandler注释为不同类型的异常添加更多功能。

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {

private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(MethodArgumentNotValidException.class)
public void handleJsonException(HttpServletResponse response, Exception ex) {
    prepareErrorResponse(response,UNPROCESSABLE_ENTITY,"");
}


private void prepareErrorResponse(HttpServletResponse response, HttpStatus status, String apiError) {
    response.setStatus(status.value());
    try(PrintWriter writer = response.getWriter()) {
        new ObjectMapper().writeValue(writer, apiError);
    } catch (IOException ex) {
        logger.error("Error writing string to response body", ex);
    }
}
}