【问题标题】:How to get the name of the key while handling DataIntegrityViolationException?如何在处理 DataIntegrityViolationException 时获取密钥的名称?
【发布时间】:2021-04-07 04:15:27
【问题描述】:

我在应用程序级别使用GenericExceptionHandling

@ControllerAdvice
public class GlobalExceptionHandler {
    
    // Handle the DataIntegrityViolationException
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<?> customDataIntegrityViolationException
                                (DataIntegrityViolationException exception) {
        String message = "This {key} is already exist";
        ErrorDetails errorDetals = new ErrorDetails(new Date(), message, exception.getCause().getMessage());
        return new ResponseEntity<Object>(errorDetals, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}

我想获取导致错误的键的名称。 IE。 {钥匙}。我用谷歌搜索但没有得到任何解决我问题的答案。如果有人做过这种工作,请提出一种方法。

【问题讨论】:

标签: java spring spring-boot hibernate spring-mvc


【解决方案1】:

我猜你应该搜索异常消息,例如

      try{
            userRepository.save(user);
        }
        catch (DataIntegrityViolationException ex){

            if(ex.getMessage().contains("unique_username")){
                throw new DataIntegrityViolationException("The username: "+user.getUsername()+" is duplicated");
            }
            else if(ex.getMessage().contains("unique_email")){
                throw new DataIntegrityViolationException("The email: "+user.getEmail()+" is duplicated");
            }

            else {
                throw new DataIntegrityViolationException(ex.getMessage());
            }

        }

为了更好地搜索约束,您可以指定约束名称,例如

@Entity
@Table(name = "user_tbl",
uniqueConstraints = {@UniqueConstraint(columnNames ="username", name = "unique_username"),
               
                    @UniqueConstraint(columnNames ="email", name = "unique_email")})


public class User {

    String username;
    String email;
    .
    .
    .
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2013-05-30
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2014-01-26
    相关资源
    最近更新 更多