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");
}
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With