Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

spring valid request body custom message

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

        @Override
        protected ResponseEntity<Object> handleMethodArgumentNotValid(
                MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

           // ex.getBindingResult(): extract the bind result for default message. 
              String errorResult = ex.getBindingResult().toString();
             CustomizedExceptionHandlerResponse exceptionResponse = new CustomizedExceptionHandlerResponse(
                    errorResult, new Date(), request.getDescription(false));

            return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
        }


}

class CustomizedExceptionHandlerResponse {

   private String message;
   private String status;
   private Date timestamp;

   // constuctor, setters, getters...
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #spring #valid #request #body #custom #message
ADD COMMENT
Topic
Name
2+3 =