Spring Boot 错误:重复的键值违反SQL请求中的唯一约束

t3psigkw  于 2024-01-06  发布在  Spring
关注(0)|答案(2)|浏览(230)

我在数据库中有一个唯一的电子邮件列值的约束。我进入日志错误:

  1. org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_7felfliwfxsdp14appb56m2c5"
  2. Detail: Key (email)=(strijdvjjng) already exists.

字符串
作为POST请求的响应,我得到:

  1. "timestamp": "2023-12-27T16:05:36.052+00:00",
  2. "status": 500,
  3. "error": "Internal Server Error",


你知道我如何从Sping Boot 端点返回正确的错误消息吗:

  1. "timestamp": "2023-12-27T16:05:36.052+00:00",
  2. "status": 500,
  3. "error": "Email already exists.",


  1. {
  2. "Email already exists."
  3. }


我需要实现一个自定义处理程序还是有更好的解决方案?

9njqaruj

9njqaruj1#

是的,最好的方法是创建一个自定义的异常和异常处理程序:
范例:

  1. public class EmailException extends RuntimeException {
  2. public EmailException(String message) {
  3. super(message);
  4. }
  5. }
  6. public class ErrorResponse {
  7. private LocalDateTime timestamp;
  8. private int status;
  9. private String error;
  10. // Constructors, getters, and setters
  11. }

字符串
你可以创建controller advice或者简单地添加一个exception handler到你的控制器类,这取决于你:

  1. @RestControllerAdvice
  2. public class GlobalExceptionHandler {
  3. @ExceptionHandler(EmailException.class)
  4. public ResponseEntity<ErrorResponse> handleEmailExistsException(EmailException ex) {
  5. ErrorResponse errorResponse = new ErrorResponse(LocalDateTime.now(), HttpStatus.BAD_REQUEST.value(), ex.getMessage());
  6. return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
  7. }
  8. }


在您的服务中:

  1. @Service
  2. public class UserService {
  3. public void createUser(User user) {
  4. try {
  5. } catch (ConstraintException e) {
  6. throw new EmailException("Email already exists.");
  7. }
  8. }
  9. }

展开查看全部
rryofs0p

rryofs0p2#

要检查您的业务约束,如“电子邮件地址必须是唯一的”,您应该执行查询以确定电子邮件是否是唯一的,作为业务要求检查的一部分。如果电子邮件地址不是唯一的,则抛出自定义异常。然后,您可以使用全局异常处理程序等来自定义响应和代码。

相关问题