title: Registration form if email address already exist then throw an exception using Springboot and Jpa
body: <p>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?</p>
  <p>Controller class:</p>
  <pre><code>@RestController
  public class RegistrationController {
  
      @Autowired
      private RegistrationService service;
  
      @PostMapping(&quot;/registeruser&quot;)
      public  User registerUser(@RequestBody User user) throws Exception {
          
          String tempEmailId = user.getEmailId();
          if(tempEmailId !=null &amp;&amp; !&quot;&quot;.equals(tempEmailId)) {
              User userObject = service.fetchUserByEmailId(tempEmailId);
              if(userObject!=null) {
                  throw new Exception(&quot;User with &quot;+tempEmailId+&quot; is already exist&quot;);
              }
              
          }
              
          User userObject = null;
          userObject = service.saveUser(user);
          return userObject;
      }
  </code></pre>
  <p>Repository:</p>
  <pre><code>public interface RegistrationRepository extends JpaRepository&lt;User, Integer&gt; {
  
      public User findByEmailId(String emailId);   
  } 
  </code></pre>
  <p>Service:</p>
  <pre><code>@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);   
      }
  }
  </code></pre>
  <p>Here is JSON response so I want my message printed but somehow not happening:</p>
  <pre><code>{
      &quot;timestamp&quot;: &quot;2020-08-26T06:28:01.369+00:00&quot;,
      &quot;status&quot;: 500,
      &quot;error&quot;: &quot;Internal Server Error&quot;,
      &quot;message&quot;: &quot;&quot;,
      &quot;path&quot;: &quot;/registeruser&quot;
  }
  </code></pre>