JDBC exception handling in Spring-mvc












0















I am implementing a REST api webservice which is fetching data from a MySql database. It is written here that we dont need to handle database exception explicitly. I have catch blocks in the Service layer. I have the following questions.



1- How do i send the appropriate error message to the respective model view from the catch block?



2- Is Service the right layer to catch the exception?



I have the following code



Controller



    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute User user, BindingResult result)
{
ModelAndView mv = new ModelAndView();

validator.validate(user, result);
if(result.hasErrors()) {
mv.setViewName("addUser");
}
else {
service.saveUser(user);
mv.setViewName("redirect:/users/listAllUsers");
}
return mv;
}


Service



public void saveUser(User user) {
try {
userDao.saveUser(user);
} catch(DuplicateKeyException e) {
//Here i want to send "User already exist"
} catch(DataAccessException e) {
//Here i want to send "Databae unreachable"
}
}


UserDAO



public void saveUser(User user) {
String sql = "INSERT INTO User (fname, lname, address, phone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, user.getFname(), user.getLname(),
user.getAddress(), user.getPhone());
}
}









share|improve this question

























  • Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

    – Almett
    Nov 22 '18 at 1:59
















0















I am implementing a REST api webservice which is fetching data from a MySql database. It is written here that we dont need to handle database exception explicitly. I have catch blocks in the Service layer. I have the following questions.



1- How do i send the appropriate error message to the respective model view from the catch block?



2- Is Service the right layer to catch the exception?



I have the following code



Controller



    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute User user, BindingResult result)
{
ModelAndView mv = new ModelAndView();

validator.validate(user, result);
if(result.hasErrors()) {
mv.setViewName("addUser");
}
else {
service.saveUser(user);
mv.setViewName("redirect:/users/listAllUsers");
}
return mv;
}


Service



public void saveUser(User user) {
try {
userDao.saveUser(user);
} catch(DuplicateKeyException e) {
//Here i want to send "User already exist"
} catch(DataAccessException e) {
//Here i want to send "Databae unreachable"
}
}


UserDAO



public void saveUser(User user) {
String sql = "INSERT INTO User (fname, lname, address, phone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, user.getFname(), user.getLname(),
user.getAddress(), user.getPhone());
}
}









share|improve this question

























  • Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

    – Almett
    Nov 22 '18 at 1:59














0












0








0








I am implementing a REST api webservice which is fetching data from a MySql database. It is written here that we dont need to handle database exception explicitly. I have catch blocks in the Service layer. I have the following questions.



1- How do i send the appropriate error message to the respective model view from the catch block?



2- Is Service the right layer to catch the exception?



I have the following code



Controller



    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute User user, BindingResult result)
{
ModelAndView mv = new ModelAndView();

validator.validate(user, result);
if(result.hasErrors()) {
mv.setViewName("addUser");
}
else {
service.saveUser(user);
mv.setViewName("redirect:/users/listAllUsers");
}
return mv;
}


Service



public void saveUser(User user) {
try {
userDao.saveUser(user);
} catch(DuplicateKeyException e) {
//Here i want to send "User already exist"
} catch(DataAccessException e) {
//Here i want to send "Databae unreachable"
}
}


UserDAO



public void saveUser(User user) {
String sql = "INSERT INTO User (fname, lname, address, phone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, user.getFname(), user.getLname(),
user.getAddress(), user.getPhone());
}
}









share|improve this question
















I am implementing a REST api webservice which is fetching data from a MySql database. It is written here that we dont need to handle database exception explicitly. I have catch blocks in the Service layer. I have the following questions.



1- How do i send the appropriate error message to the respective model view from the catch block?



2- Is Service the right layer to catch the exception?



I have the following code



Controller



    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute User user, BindingResult result)
{
ModelAndView mv = new ModelAndView();

validator.validate(user, result);
if(result.hasErrors()) {
mv.setViewName("addUser");
}
else {
service.saveUser(user);
mv.setViewName("redirect:/users/listAllUsers");
}
return mv;
}


Service



public void saveUser(User user) {
try {
userDao.saveUser(user);
} catch(DuplicateKeyException e) {
//Here i want to send "User already exist"
} catch(DataAccessException e) {
//Here i want to send "Databae unreachable"
}
}


UserDAO



public void saveUser(User user) {
String sql = "INSERT INTO User (fname, lname, address, phone)"
+ " VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, user.getFname(), user.getLname(),
user.getAddress(), user.getPhone());
}
}






java spring rest spring-mvc spring-jdbc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 0:52







Daim

















asked Nov 22 '18 at 0:15









DaimDaim

326




326













  • Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

    – Almett
    Nov 22 '18 at 1:59



















  • Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

    – Almett
    Nov 22 '18 at 1:59

















Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

– Almett
Nov 22 '18 at 1:59





Do you meant to display the error message in JSP page by send the appropriate error message to the respective model view?

– Almett
Nov 22 '18 at 1:59












2 Answers
2






active

oldest

votes


















2














@dbreaux 's answer is correct.You should customize an exception.



public class UserException extends RuntimeException {
// You can add some custom variables
// such as error codes, error types, etc.
}


Then,you should define a ControllerAdvice to handle this Exception:



import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class UserControllerAdvice{

@ExceptionHandler(value = UserException.class)
public ModelAndView handleUserException(UserException ex){

// Generate corresponding results(ModelAndView) based on exception.
// example: Put the error message to model.
return new ModelAndView("prompt_page",ex.getMessage());
}
}


Last,you can throws UserException in your Service.



public void saveUser(User user) {
try {
userDao.saveUser(user);
} catch(DuplicateKeyException e) {
throw new UserException("User already exist");
} catch(DataAccessException e) {
throw new UserException("Databae unreachable");
}
}





share|improve this answer































    0














    You want to isolate the web-specific behaviors from the service layer, and from the data layer, and I think the best way to do that is to throw a new, checked, domain-specific Exception that matches the meaning of each case you want to handle differently in the Controller.



    For example, DuplicateUserException, SystemUnavailableException. Then the Controller catches those and adds the correct case to the Model.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422217%2fjdbc-exception-handling-in-spring-mvc%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      @dbreaux 's answer is correct.You should customize an exception.



      public class UserException extends RuntimeException {
      // You can add some custom variables
      // such as error codes, error types, etc.
      }


      Then,you should define a ControllerAdvice to handle this Exception:



      import org.springframework.web.bind.annotation.ControllerAdvice;
      import org.springframework.web.bind.annotation.ExceptionHandler;

      @ControllerAdvice
      public class UserControllerAdvice{

      @ExceptionHandler(value = UserException.class)
      public ModelAndView handleUserException(UserException ex){

      // Generate corresponding results(ModelAndView) based on exception.
      // example: Put the error message to model.
      return new ModelAndView("prompt_page",ex.getMessage());
      }
      }


      Last,you can throws UserException in your Service.



      public void saveUser(User user) {
      try {
      userDao.saveUser(user);
      } catch(DuplicateKeyException e) {
      throw new UserException("User already exist");
      } catch(DataAccessException e) {
      throw new UserException("Databae unreachable");
      }
      }





      share|improve this answer




























        2














        @dbreaux 's answer is correct.You should customize an exception.



        public class UserException extends RuntimeException {
        // You can add some custom variables
        // such as error codes, error types, etc.
        }


        Then,you should define a ControllerAdvice to handle this Exception:



        import org.springframework.web.bind.annotation.ControllerAdvice;
        import org.springframework.web.bind.annotation.ExceptionHandler;

        @ControllerAdvice
        public class UserControllerAdvice{

        @ExceptionHandler(value = UserException.class)
        public ModelAndView handleUserException(UserException ex){

        // Generate corresponding results(ModelAndView) based on exception.
        // example: Put the error message to model.
        return new ModelAndView("prompt_page",ex.getMessage());
        }
        }


        Last,you can throws UserException in your Service.



        public void saveUser(User user) {
        try {
        userDao.saveUser(user);
        } catch(DuplicateKeyException e) {
        throw new UserException("User already exist");
        } catch(DataAccessException e) {
        throw new UserException("Databae unreachable");
        }
        }





        share|improve this answer


























          2












          2








          2







          @dbreaux 's answer is correct.You should customize an exception.



          public class UserException extends RuntimeException {
          // You can add some custom variables
          // such as error codes, error types, etc.
          }


          Then,you should define a ControllerAdvice to handle this Exception:



          import org.springframework.web.bind.annotation.ControllerAdvice;
          import org.springframework.web.bind.annotation.ExceptionHandler;

          @ControllerAdvice
          public class UserControllerAdvice{

          @ExceptionHandler(value = UserException.class)
          public ModelAndView handleUserException(UserException ex){

          // Generate corresponding results(ModelAndView) based on exception.
          // example: Put the error message to model.
          return new ModelAndView("prompt_page",ex.getMessage());
          }
          }


          Last,you can throws UserException in your Service.



          public void saveUser(User user) {
          try {
          userDao.saveUser(user);
          } catch(DuplicateKeyException e) {
          throw new UserException("User already exist");
          } catch(DataAccessException e) {
          throw new UserException("Databae unreachable");
          }
          }





          share|improve this answer













          @dbreaux 's answer is correct.You should customize an exception.



          public class UserException extends RuntimeException {
          // You can add some custom variables
          // such as error codes, error types, etc.
          }


          Then,you should define a ControllerAdvice to handle this Exception:



          import org.springframework.web.bind.annotation.ControllerAdvice;
          import org.springframework.web.bind.annotation.ExceptionHandler;

          @ControllerAdvice
          public class UserControllerAdvice{

          @ExceptionHandler(value = UserException.class)
          public ModelAndView handleUserException(UserException ex){

          // Generate corresponding results(ModelAndView) based on exception.
          // example: Put the error message to model.
          return new ModelAndView("prompt_page",ex.getMessage());
          }
          }


          Last,you can throws UserException in your Service.



          public void saveUser(User user) {
          try {
          userDao.saveUser(user);
          } catch(DuplicateKeyException e) {
          throw new UserException("User already exist");
          } catch(DataAccessException e) {
          throw new UserException("Databae unreachable");
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 3:50









          王瑞环王瑞环

          343




          343

























              0














              You want to isolate the web-specific behaviors from the service layer, and from the data layer, and I think the best way to do that is to throw a new, checked, domain-specific Exception that matches the meaning of each case you want to handle differently in the Controller.



              For example, DuplicateUserException, SystemUnavailableException. Then the Controller catches those and adds the correct case to the Model.






              share|improve this answer




























                0














                You want to isolate the web-specific behaviors from the service layer, and from the data layer, and I think the best way to do that is to throw a new, checked, domain-specific Exception that matches the meaning of each case you want to handle differently in the Controller.



                For example, DuplicateUserException, SystemUnavailableException. Then the Controller catches those and adds the correct case to the Model.






                share|improve this answer


























                  0












                  0








                  0







                  You want to isolate the web-specific behaviors from the service layer, and from the data layer, and I think the best way to do that is to throw a new, checked, domain-specific Exception that matches the meaning of each case you want to handle differently in the Controller.



                  For example, DuplicateUserException, SystemUnavailableException. Then the Controller catches those and adds the correct case to the Model.






                  share|improve this answer













                  You want to isolate the web-specific behaviors from the service layer, and from the data layer, and I think the best way to do that is to throw a new, checked, domain-specific Exception that matches the meaning of each case you want to handle differently in the Controller.



                  For example, DuplicateUserException, SystemUnavailableException. Then the Controller catches those and adds the correct case to the Model.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 22 '18 at 3:17









                  dbreauxdbreaux

                  4,19111550




                  4,19111550






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422217%2fjdbc-exception-handling-in-spring-mvc%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith