Registration form if email address already exist then throw an exception using Springboot and Jpa

Viewed 2705

I want to create a form that I can submit it and data store in h2. If email address is already in h2 then throw an exception. I have four packages(Controller, Model, Service, Repository). I dont get my exception message when I use an email that already exist in h2. Can you please help me where is the issue?

Controller class:

@RestController
public class RegistrationController {

    @Autowired
    private RegistrationService service;

    @PostMapping("/registeruser")
    public  User registerUser(@RequestBody User user) throws Exception {
        
        String tempEmailId = user.getEmailId();
        if(tempEmailId !=null && !"".equals(tempEmailId)) {
            User userObject = service.fetchUserByEmailId(tempEmailId);
            if(userObject!=null) {
                throw new Exception("User with "+tempEmailId+" is already exist");
            }
            
        }
            
        User userObject = null;
        userObject = service.saveUser(user);
        return userObject;
    }

Repository:

public interface RegistrationRepository extends JpaRepository<User, Integer> {

    public User findByEmailId(String emailId);   
} 

Service:

@Service
public class RegistrationService {

    @Autowired 
    private RegistrationRepository repo;
    
    public User saveUser(User user) {
        return repo.save(user);
    }
    
    public User fetchUserByEmailId(String email) { 
        return repo.findByEmailId(email);   
    }
}

Here is JSON response so I want my message printed but somehow not happening:

{
    "timestamp": "2020-08-26T06:28:01.369+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/registeruser"
}
3 Answers

Same kind of problem i got. what i did is rather than checking the object inside the if condition you better try to check with attribute of the object. eg if(userObject.getEmailId().isEmpty()) { throw new Exception("User with "+tempEmailId+" is already exist"); } this worked for me.

You can configure a Spring ExceptionHandler to customize your response body with exception messages:

@ControllerAdvice
public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {


  @Autowired
  public GlobalExceptionMapper() {
  }


  @ExceptionHandler(value = {Exception.class})
  protected ResponseEntity<Object> handleBusinessException(Exception ex, WebRequest request) {

    return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
  }

If you are using Spring Boot version 2.3 or higher, the property server.error.include-message must be set to always at application.properties file.

Related