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

t3psigkw  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(66)

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

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

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

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


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

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


{
   "Email already exists."
}


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

9njqaruj

9njqaruj1#

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

public class EmailException extends RuntimeException {
    public EmailException(String message) {
        super(message);
    }
}

public class ErrorResponse {
    private LocalDateTime timestamp;
    private int status;
    private String error;

    // Constructors, getters, and setters
}

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

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EmailException.class)
    public ResponseEntity<ErrorResponse> handleEmailExistsException(EmailException ex) {
        ErrorResponse errorResponse = new ErrorResponse(LocalDateTime.now(), HttpStatus.BAD_REQUEST.value(), ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
   
}


在您的服务中:

@Service
public class UserService {

    public void createUser(User user) {
        try {
            
        } catch (ConstraintException e) {
             throw new EmailException("Email already exists.");              
        }
    }
}

rryofs0p

rryofs0p2#

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

相关问题