I create REST web-service with Spring Boot. I would like to know what is a better way to handle exceptions in a controller. I have seen other questions and didn’t found an answer.
My controller:
@GetMapping public ResponseEntity<?> saveMyUser(){ MyUser myUser = new MyUser(“Anna”); //throws SQLException MyUserDetails userDetails = userService.saveMyUser(myUser); //if successful return ResponseBody.ok(userDetails); } saveMyUser() method of UserService:
public MyUserDetails saveUser(MyUser) throws SQLException {...} So at this point I have at least 2 simple options:
Add exception to method signature. Here I may rely on Spring Boot to pass all information about exception and status code to a client. However do not know if it is a reliable approach.
Surround with try/catch and pass all information about exceptions manually.
What is a better simple way?
throws Exception(you don't care). Then annotate a method with@ExceptionHandler: docs.spring.io/spring/docs/current/javadoc-api/org/…JdbcTempaltewhich already handles all of this.DataAccessExceptionthrown by theJdbcTemplateas it is an unchecked (aka.RuntimeException). If you want to do something specific in this controller or your code yo ucan use an@ExceptionHandler.