Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

validate data type in request body spring validation

package com.tericcabrel.hotel.exceptions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
  @Override
  protected ResponseEntity<Object> handleMethodArgumentNotValid(
      MethodArgumentNotValidException ex, HttpHeaders headers,
      HttpStatus status, WebRequest request) {

    Map<String, List<String>> body = new HashMap<>();

    List<String> errors = ex.getBindingResult()
        .getFieldErrors()
        .stream()
        .map(DefaultMessageSourceResolvable::getDefaultMessage)
        .collect(Collectors.toList());

    body.put("errors", errors);

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

PREVIOUS NEXT
Code Example
Java :: check if object is a string java 
Java :: Reverse Order Output for Java Do-While Loop 
Java :: what does import com.sun.glass do 
Java :: Log exception details to string 
Java :: clear datepicker javafx 
Java :: Goodbye to "Inspect Element" 
Java :: navigation view item selected 
Java :: getcokor from drawable in java android studio 
Java :: Java Target annotations attributes 
Java :: java how to make a recrussive boolean function 
Java :: test spring cloud stream 
Java :: collapse recycler view on new item click 
Java :: how to return list in java 
Java :: spring mvc aop transaction management 
Java :: arraylist character agregar elementos en java 
Java :: Spring AOP 
Java :: java setting logging with rotation logback 
Java :: java ternärer operator 
Java :: java package naming convention plural singular 
Java :: MinimumAndMaximum 
Java :: how to use java code to print with a network printer 
Java :: Uri/beecrowd problem no 1118 solution in Java 
Java :: java format zero padded binary 
Java :: scroll 
Java :: java digit in number 
Java :: java join list 
Java :: java or cpp 
Java :: create thread 
Java :: java get class by string name 
Java :: my animal list 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =