【问题标题】:Can we directly throw ResponseStatusException from service layer without throwing custom exception and handling at the controller level?我们可以直接从服务层抛出 ResponseStatusException 而不抛出自定义异常并在控制器级别进行处理吗?
【发布时间】:2020-04-24 19:39:06
【问题描述】:

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 并抛出 ResponseStatusException,为什么我们必须再次捕获自定义异常而不是 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");
      }
    }
}

【问题讨论】:

  • 不要。 ResponseStatusException 是特定于 Web 的例外,您不想将服务层绑定到 Web。而是使用@ExceptionHandlerUserNotFoundException 转换为您想要的,而不是添加try/catch 块。
  • 完全同意@M.Deinum。如果您不想创建专用的@ExceptionHandler,也可以使用@ResponseStatus 注释您的UserNotFoundException。如果您需要更详细的错误处理和报告,另一种选择是使用Errors Spring Boot Starter

标签: java spring spring-boot exception


【解决方案1】:

正如 cmets 中提到的,您可以在错误中创建映射。那么你就不需要在控制器中使用 try 块了。

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);
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多