2
比方說,我有以下運行時異常:哪裏扔HTTP運行時異常
@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public class ExpectationsFailedException extends RuntimeException {
public ExpectationsFailedException(String message) {
super(message);
}
}
我的問題是,如果它是確定扔前面的HTTP例外,在我服務層或者我應該把它從我的控制器:
@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");
}
}
}
控制器異常拋出的解決方案將是以下:
@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");
}
}
}
和我的控制器中
@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無關的其他上下文中使用該服務。
我會去第二個。
您認爲如何?