【发布时间】:2020-12-16 23:19:11
【问题描述】:
我有以下 Java 方法:
public Class createClass(Class class) {
try {
// retrieve the professor of the class and check if he exists
Professor professorFound = professorRepository.findById(class.getProfessorId());
if (professorFound != null) {
// if the professor exists, then check if he already has a class
// with the same id
List<Class> classes = professorFound.getClasses();
List<Class> classFound = classes.stream().... // loop to find the class...
// if he has, throw an exception
if(!classFound.isEmpty()) {
throw new ClassAlreadyRegisteredException();
} else {
// if he does not have, then create the class
Class class = new Class();
professorFound.getClasses().add(class);
return professorRepository.save(professorFound);
}
} else {
// if the professor does not exist, throw an exception
throw new ProfessorNotFoundException();
} catch (Exception e) {
// if there is any other error during the communication with the database,
// throw a generic IOException
throw new ClassIOException();
}
}
基本上,我需要的是抛出特定的异常(如果请求中通知的教授不存在,或者教授已经有一个具有相同 id 的课程),或者如果有任何抛出一个通用的IOException与数据库通信过程中的其他错误。
但是,按照我开发的方式,如果抛出任何特定的Exception,try 块将捕获异常并抛出通用 IOException。
我该如何解决这个问题?
我很想了解这种情况下的最佳做法。 我应该分别捕获每个特定异常并抛出两次吗? 这是一个好习惯吗?
编辑:
这就是我的ClassAlreadyRegisteredException 的样子:
public class ClassAlreadyRegisteredException extends ApiException {
private static final long serialVersionUID = 1L;
public ClassAlreadyRegisteredException(String code, String message, String developerMessage, String origin, HttpStatus status) {
super(code,message,developerMessage,origin, status);
}
}
这就是我的ApiException 的样子:
@Data
@AllArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class ApiException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String code;
private String userMessage;
private String developerMessage;
private String origin;
private HttpStatus status;
}
提前致谢。
【问题讨论】:
-
你绝对应该改变你的
Class类的名字;永远不要将一个类命名为与java.lang中的任何东西相同的东西。 -
谢谢,你是对的。实际上
Class和Professor并不是类的原始名称;为了更好地解释问题,我使用了这些名称。
标签: java spring-boot