我们是否可以直接从服务层抛出ResponsueStatusException,而不在控制器级别抛出自定义异常和处理?
2022-09-04 22:50:16
Spring 5 引入了 ResponseStatusException,直接从服务层抛出此异常是一种很好的做法。
案例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");
}
}
}
案例2:或者我们需要使用自定义异常并在控制器级别处理它?在这种情况下,我们正在捕获CustomException并抛出ResponsiveStatusException,为什么我们必须再次捕获自定义异常而不是使用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");
}
}
}