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

user630209 picture user630209 · Jun 7, 2018 · Viewed 7.5k times · Source

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

Answer

Afridi picture Afridi · Jun 7, 2018

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