0

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:

  1. 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.

  2. Surround with try/catch and pass all information about exceptions manually.

What is a better simple way?

6
  • 2
    do not handle them yourself. let all your methods in controller throws Exception (you don't care). Then annotate a method with @ExceptionHandler: docs.spring.io/spring/docs/current/javadoc-api/org/… Commented May 23, 2019 at 8:31
  • 1
    you have a number of options: exception-handling-for-rest-with-spring Commented May 23, 2019 at 8:35
  • 1
    Don't throw SQLExcpetion. That basicallyl means you are using plain JDBC. Iinstead use the JdbcTempalte which already handles all of this. Commented May 23, 2019 at 8:39
  • 1
    In additional Spring Boot will then handle the DataAccessException thrown by the JdbcTemplate as it is an unchecked (aka. RuntimeException). If you want to do something specific in this controller or your code yo ucan use an @ExceptionHandler. Commented May 23, 2019 at 8:43
  • @spi Do not want to post it as an answer? That is what I needed. Thanks. Commented May 23, 2019 at 8:46

1 Answer 1

5

You can create an additional class with @ControllerAdivce annotation and later you will be able to write custom response logic for each exception e.g:

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler({SQLException.class}) public ResponseEntity<Object> sqlError(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Some SQL exception occured"); } } 

Also, you can extend ResponseEntityExceptionHandler and override the default behavior for mapping from exceptions to HTTP response.

Also, take a look at this, it holds very usefull information for your case.

Sign up to request clarification or add additional context in comments.

1 Comment

But when I try to extend from ResponseEntityExceptionHandler as in the material then an annotation @Valid in a controller method stops sending information to a client, only a status code. Do not know why. Your method works just fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.