Spring验证返回长错误消息,而不仅仅是自定义消息

时间:2018-06-07 09:12:16

标签: spring-boot spring-validator

Spring验证返回长错误消息,而不是自定义一次。

这是dto中的代码部分。

public class RequestDto implements Serializable {
    @NotNull(message="{id.required}")
    private Long id;

}

在控制器中添加@Valid作为输入。

@RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml",
            "application/json" })
    public @ResponseBody ResultDecorator saveRequest(
            @Valid @RequestBody RequestDto msaDisabScreenRequestDto) throws Exception {

}

API返回以下错误。

<message>Validation failed for argument at index 0 in method: public om.gov.moh.msa.framework.resolver.ResultDecorator om.controller.MaController.saveRequest(om..dto.RequestDto) throws java.lang.Exception, with 1 error(s): [Field error in object 'requestDto' on field 'id': rejected value [null]; codes [NotNull.requestDto.id,NotNull.id,NotNull.java.lang.Long,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [requestDto.id,id]; arguments []; default message [civilId]]; **default message [ID is required.]]** </message>

此处自定义消息最后出现。 (默认消息[ID是必需的。

使用Controller建议进行全局异常,我重写了handleMethodArgumentNotValid。如何在此处仅返回自定义消息?

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {



   /**
    * Spring validation related exception
    */
   @Override
   protected ResponseEntity<Object> handleMethodArgumentNotValid(
           MethodArgumentNotValidException ex,
           HttpHeaders headers,
           HttpStatus status,
           WebRequest request) {

       ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
       apiError.setMessage(ex.getMessage());
       return buildResponseEntity(apiError);
   }
}

3 个答案:

答案 0 :(得分:2)

您可以获取默认/自定义消息,例如result.getFieldError("yourFieldName").getDefaultMessage()

您可以通过控制器方法捕获错误消息,该方法应该如下所示

    @RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml", "application/json" })
    public @ResponseBody ResultDecorator saveRequest(@Valid @RequestBody RequestDto msaDisabScreenRequestDto, BindingResult result) throws Exception {
        if(result.hasErrors()){
            String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
        }
    }

或通过全局异常处理程序

更新

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {



       /**
        * Spring validation related exception
        */
       @Override
       protected ResponseEntity<Object> handleMethodArgumentNotValid(
               MethodArgumentNotValidException ex,
               HttpHeaders headers,
               HttpStatus status,
               WebRequest request) {

           //New Code
           BindingResult bindingResult = ex.getBindingResult();
           String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
//---------------
           ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
           apiError.setMessage(errorMessage);
           return buildResponseEntity(apiError);
       }
    }

答案 1 :(得分:0)

谢谢Afridi, 创建了一个字符串缓冲区并将所有错误消息添加到其中。

   /**
    * Spring validation related exception
    */
   @Override
   protected ResponseEntity<Object> handleMethodArgumentNotValid(
           MethodArgumentNotValidException ex,
           HttpHeaders headers,
           HttpStatus status,
           WebRequest request) {

       final StringBuffer errors = new StringBuffer();
       ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
       for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
           errors.append("\n");
           errors.append(error.getField() + ": " + error.getDefaultMessage());
       }
       apiError.setMessage(errors.toString());
       return buildResponseEntity(apiError);
   }

答案 2 :(得分:0)

正如Afridi在@ControllerAdvice中所说,也可以做到这一点:

@ExceptionHandler(value = MethodArgumentNotValidException.class)
@SuppressWarnings("unchecked")
@ResponseBody
public Result methodArgumentNotValidExceptionHandler(HttpServletRequest req, HttpServletResponse response, MethodArgumentNotValidException e) throws IOException {
    String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();

    // todo return to your custom result
}

有两点:

  • 异常类为MethodArgumentNotValidException
  • 第一个错误getDefaultMessage()可以在Annotation中获取您的自定义消息