【发布时间】:2021-07-09 10:11:18
【问题描述】:
我正在使用 Spring Boot 和 Spring Data Rest 开发一个后端。我需要抛出一个自定义异常,而不是具有不同结构的 Spring Data Rest 异常。
这是我编写的代码,但它不会抛出我的异常,而是一个通用的 RuntimeException
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Locale;
@ControllerAdvice(annotations = RepositoryRestController.class)
public class RestRepositoryExceptionHandler {
@ExceptionHandler({DataIntegrityViolationException.class})
public RuntimeException handle(Exception e, Locale locale) {
throw new RuntimeException("REST_REPOSITORY_EXCEPTION", e);
// throw new RuntimeException("DATA_ALREADY_EXISTS");
}
}
这是一个存储库
import it.edistribuzione.smartgrid.model.User;
import lombok.NonNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.Optional;
@RepositoryRestResource(path = "users")
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
boolean existsById(@NonNull Long id);
}
【问题讨论】:
标签: java spring spring-boot spring-data-jpa