Spring validation returns long error messages, not just the customized message

我的未来我决定 提交于 2020-07-18 07:52:06

问题


Spring validation returns long error message instead of the customized once.

This is the section of code in the dto.

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

}

In controller added the @Valid for input.

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

}

API returns the following error.

<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>

Here the custom message is present at the end. (default message [ID is required.)

Using Controller advice for global exception and I'm overriding handleMethodArgumentNotValid. How can I return only the custom message here?

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

回答1:


You can get default/custom message like result.getFieldError("yourFieldName").getDefaultMessage()

You can catch error messages either through controller method which should look like this

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

Or through Global Exception handler

Updated

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



回答2:


As Afridi said in @ControllerAdvice can do this also:

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

There are two point :

  • Exception class is MethodArgumentNotValidException
  • The first Error getDefaultMessage() can get your custom message in Annotation



回答3:


Thanks Afridi, Created a string buffer and added all the error messages into that.

   /**
    * 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);
   }


来源:https://stackoverflow.com/questions/50737381/spring-validation-returns-long-error-messages-not-just-the-customized-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!