gpt4 book ai didi

java - 如何在 Java 中处理 PSQLException?

转载 作者:行者123 更新时间:2023-11-29 11:32:41 31 4
gpt4 key购买 nike

我对我的一个实体有一个唯一的约束,每当我收到一个 PSQLException,只要违反该约束就会发生,我想用一个错误的请求来响应。

这是我尝试实现的异常处理程序:

@ControllerAdvice
public class DatabaseExceptionHandler {
@ExceptionHandler(value = PSQLException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void handleDatabaseExceptions(PSQLException e) {
// i want to respond with a bad request only when this condition is satisfied
//
// if (e.getSQLState().equals("23505")) {
//
// }
}

}

这是模型在数据库中的保存位置:

 public DepartmentForHoliday setDepartment(DepartmentForHoliday department) {
if (department.getDepartmentId() == null) {
Department savedDepartment = new Department();
savedDepartment.setName(department.getName());
try {
departmentRepository.save(savedDepartment);
} catch (PSQLException e) {
/*here i have a compiler error which says that this exception is never thrown in the corresponding try block, but where ?*/
}
}

这是我添加重复条目时抛出的异常:

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_1t68827l97cwyxo9r1u6t4p7d"
Detail: Key (name)=(Tech) already exists.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2458) ~[postgresql-9.4.1211.jre7.jar:9.4.1211.jre7]

如何处理 PSQLExceptions?我应该将自己的异常作为包装器还是如何解决这个问题?

最佳答案

关键问题是 PSQLException 被包装到一些 Spring 异常中(我从你的代码中假设);你必须打开它(例如使用 Guava 的 Throwables ):

public DepartmentForHoliday setDepartment(DepartmentForHoliday department) {
if (department.getDepartmentId() == null) {
Department savedDepartment = new Department();
savedDepartment.setName(department.getName());
try {
departmentRepository.save(savedDepartment);
} catch (RuntimeException e) {
Throwable rootCause = com.google.common.base.Throwables.getRootCause(e);
if (rootCause instanceof SQLException) {
if ("23505".equals(((SQLException) rootCause).getSQLState())) {
// do smth interesting :)
}
}
}
}
}

完成后,您可以抛出自定义异常并在 DatabaseExceptionHandler 中处理它

关于java - 如何在 Java 中处理 PSQLException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301779/

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