Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we directly throw ResponseStatusException from service layer without throwing custom exception and handling at the controller level?

Spring 5 has introduced ResponseStatusException, is it a good practice to throw this exception directly from the service layer.

Case 1:

@Service
public class UserService {
    public User findUserByName(String username) {
       User user = userRepository.findByUsernName(username);
       if(null == user) {
          throw new ResponseStatusException(HttpStatus.NOT_FOUND, "user not found");
       }
    }
}

Case 2: Or do we need to use custom exception and handle it in controller level ? We are catching the CustomException and throwing ResponseStatusException in this case, why do we have to catch the custom exception again instead of going with Case 1

@Service
public class UserService {
    public User findUserByName(String username) {
       User user = userRepository.findByUsernName(username);
       if(null == user) {
          throw new UserNotFoundException("user not found");
       }
    }
}

@RestController
public class UserController {

    @GetMapping(path="/get-user")
    public ResponseEntity<User> getUser(String username) {
      try {
         userService.findUserByName(username);
      } catch (UserNotFoundException ex) {
         throw new ResponseStatusException(HttpStatus.NOT_FOUND, "user not found");
      }
    }
}
like image 269
devfreak Avatar asked Jan 07 '20 09:01

devfreak


1 Answers

As it was mentioned in comments, you can create mapping in your error. Then you do not need to use try block in controller.

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
} 
like image 180
lczapski Avatar answered Oct 25 '22 11:10

lczapski