Spring validation returns long error messages, not

2020-08-01 04:09发布

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

3条回答
贪生不怕死
2楼-- · 2020-08-01 04:23

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);
   }
查看更多
▲ chillily
3楼-- · 2020-08-01 04:25

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
查看更多
做个烂人
4楼-- · 2020-08-01 04:43

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);
       }
    }
查看更多
登录 后发表回答