├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── javatechie │ │ └── api │ │ ├── ValidationExampleApplication.java │ │ ├── advice │ │ └── ApplicationExceptionHandler.java │ │ ├── controller │ │ └── UserController.java │ │ ├── dto │ │ └── UserRequest.java │ │ ├── entity │ │ └── User.java │ │ ├── exception │ │ └── UserNotFoundException.java │ │ ├── repository │ │ └── UserRepository.java │ │ └── service │ │ └── UserService.java └── resources │ ├── application.properties │ └── application.yml └── test └── java └── com └── javatechie └── api └── ValidationExampleApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # validation-exception-handling 2 | Spring Request validation & Exception Handling Realtime example 3 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.6.6 9 | 10 | 11 | com.javatechie 12 | validation-example 13 | 0.0.1-SNAPSHOT 14 | validation-example 15 | Demo project for Spring Boot 16 | 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-validation 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | com.h2database 35 | h2 36 | runtime 37 | 38 | 39 | org.projectlombok 40 | lombok 41 | true 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | org.projectlombok 59 | lombok 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/ValidationExampleApplication.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ValidationExampleApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ValidationExampleApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/advice/ApplicationExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.advice; 2 | 3 | import com.javatechie.api.exception.UserNotFoundException; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.MethodArgumentNotValidException; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseStatus; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import org.springframework.web.bind.annotation.RestControllerAdvice; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | @RestControllerAdvice 15 | public class ApplicationExceptionHandler { 16 | 17 | 18 | @ResponseStatus(HttpStatus.BAD_REQUEST) 19 | @ExceptionHandler(MethodArgumentNotValidException.class) 20 | public Map handleInvalidArgument(MethodArgumentNotValidException ex) { 21 | Map errorMap = new HashMap<>(); 22 | ex.getBindingResult().getFieldErrors().forEach(error -> { 23 | errorMap.put(error.getField(), error.getDefaultMessage()); 24 | }); 25 | return errorMap; 26 | } 27 | 28 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 29 | @ExceptionHandler(UserNotFoundException.class) 30 | public Map handleBusinessException(UserNotFoundException ex) { 31 | Map errorMap = new HashMap<>(); 32 | errorMap.put("errorMessage", ex.getMessage()); 33 | return errorMap; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.controller; 2 | 3 | import com.javatechie.api.dto.UserRequest; 4 | import com.javatechie.api.entity.User; 5 | import com.javatechie.api.exception.UserNotFoundException; 6 | import com.javatechie.api.service.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import javax.validation.Valid; 13 | import java.util.List; 14 | 15 | @RestController 16 | @RequestMapping("/users") 17 | public class UserController { 18 | 19 | @Autowired 20 | private UserService service; 21 | 22 | @PostMapping("/signup") 23 | public ResponseEntity saveUser(@RequestBody @Valid UserRequest userRequest){ 24 | return new ResponseEntity<>(service.saveUser(userRequest), HttpStatus.CREATED); 25 | } 26 | 27 | @GetMapping("/fetchAll") 28 | public ResponseEntity> getAllUsers(){ 29 | return ResponseEntity.ok(service.getALlUsers()); 30 | } 31 | 32 | @GetMapping("/{id}") 33 | public ResponseEntity getUser(@PathVariable int id) throws UserNotFoundException { 34 | return ResponseEntity.ok(service.getUser(id)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/dto/UserRequest.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.validation.constraints.*; 8 | 9 | @Data 10 | @AllArgsConstructor(staticName = "build") 11 | @NoArgsConstructor 12 | public class UserRequest { 13 | @NotNull(message = "username shouldn't be null") 14 | private String name; 15 | @Email(message = "invalid email address") 16 | private String email; 17 | @Pattern(regexp = "^\\d{10}$",message = "invalid mobile number entered ") 18 | private String mobile; 19 | private String gender; 20 | @Min(18) 21 | @Max(60) 22 | private int age; 23 | @NotBlank 24 | private String nationality; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | 12 | @Entity 13 | @Table(name = "USERS_TBL") 14 | @Data 15 | @AllArgsConstructor(staticName = "build") 16 | @NoArgsConstructor 17 | public class User { 18 | @Id 19 | @GeneratedValue 20 | private int userId; 21 | private String name; 22 | private String email; 23 | private String mobile; 24 | private String gender; 25 | private int age; 26 | private String nationality; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/exception/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.exception; 2 | 3 | public class UserNotFoundException extends Exception{ 4 | public UserNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.repository; 2 | 3 | import com.javatechie.api.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface UserRepository extends JpaRepository { 7 | User findByUserId(int id); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/api/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api.service; 2 | 3 | import com.javatechie.api.dto.UserRequest; 4 | import com.javatechie.api.entity.User; 5 | import com.javatechie.api.exception.UserNotFoundException; 6 | import com.javatechie.api.repository.UserRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.List; 11 | 12 | @Service 13 | public class UserService { 14 | 15 | @Autowired 16 | private UserRepository repository; 17 | 18 | 19 | public User saveUser(UserRequest userRequest) { 20 | User user = User. 21 | build(0, userRequest.getName(), userRequest.getEmail(), 22 | userRequest.getMobile(), userRequest.getGender(), userRequest.getAge(), userRequest.getNationality()); 23 | return repository.save(user); 24 | } 25 | 26 | 27 | public List getALlUsers() { 28 | return repository.findAll(); 29 | } 30 | 31 | 32 | public User getUser(int id) throws UserNotFoundException { 33 | User user= repository.findByUserId(id); 34 | if(user!=null){ 35 | return user; 36 | }else{ 37 | throw new UserNotFoundException("user not found with id : "+id); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | h2: 3 | console: 4 | enabled: true 5 | datasource: 6 | url: jdbc:h2:mem:testdb 7 | 8 | 9 | server: 10 | port: 9292 -------------------------------------------------------------------------------- /src/test/java/com/javatechie/api/ValidationExampleApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.api; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ValidationExampleApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------