gpt4 book ai didi

java - 在哪里抛出 HTTP 运行时异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:59 25 4
gpt4 key购买 nike

假设我有以下运行时异常:

@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public class ExpectationsFailedException extends RuntimeException {
public ExpectationsFailedException(String message) {
super(message);
}
}

我的问题是是否可以在我的服务层中抛出之前的 HTTP 异常,或者我应该从我的 Controller 中抛出它:

@Service
public class UserService {

@Autowired
...

public void addUser(final String email, final String username, final String password){
if(parameters_are_not_valid){
throw new ExpectationsFailedException("Invalid input");
}
}

}

Controller 异常抛出解决方案如下:

@Service
public class UserService {

@Autowired
...

public void addUser(final String email, final String username, final String password) throws InvalidInputParameters {
if(parameters_are_not_valid){
throw new InvalidInputParameters("Invalid input");
}
}

}

在我的 Controller 中

@RestController
public class XController{

@Autowired
private UserService userService;

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public void addUser(@Valid @RequestBody SignUpForm form, BindingResult bindingResult){
if(bindingResult.hasErrors()){
throw new ExpectationsFailedException("Input parameters conditions were not fulfilled");
}

try {
userService.addUser(...);
}
catch(InvalidInputParameters ex){
throw new ExpectationsFailedException("Invalid service input parameters");
}
}
}

首选这些解决方案中的哪一个?为什么?我觉得我不应该在我的服务中抛出 HTTP 异常,因为我可能会在与 HTTP 无关的其他上下文中使用该服务。

我会选择第二个。

你怎么看?

最佳答案

我同意你最后的说法。您的服务层应该独立于 HTTP 或前端框架(@ResponseStatus 是 Spring MVC 注释,因此在您的服务层中使用它不是最佳实践)。

然而,您不必在服务层抛出一个异常,在 Controller 中捕获它并重新抛出另一个用 @ResponseStatus 注释的异常。只需为服务异常添加异常处理程序并从中返回适当的响应状态。您有很多选择,例如 @ExceptionHandler :

@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
@ExceptionHandler(InvalidInputParameters.class)
public void handle() {
// Do nothing, just return the status
}

您可以将此代码放入@ControllerAdvice带注释的类,以便为所有 Controller 启用它,或者如果其他地方不需要它,则仅在您的 Controller 中启用它。

关于java - 在哪里抛出 HTTP 运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com