当前位置: 首页 > 知识库问答 >
问题:

无法捕获Spring数据REST中的DataIntegrityViolationException

岳晟
2023-03-14

尝试使用ControllerAdvice处理DataIntegrityViolationException并使用Spring Boot v1.3.3和Spring Data REST v2.4.4返回自定义响应。以下是我的课程:

ExceptionControllerAdvice.java

@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(DataIntegrityViolationException.class)
public ViolationResponse handleConflictException(DataIntegrityViolationException ex) throws Exception {
    return new ViolationResponse(ex.getMessage());
}
public class ViolationResponse {

private String message;

public ViolationResponse(String message) {
    this.message = message;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
}

但我得到的是404状态,而不是这个响应:

{“时间戳”:1463382639043“状态”:404“错误”:“找不到”“异常”:“org.springframework.dao.dataintegrityviolationexception”“消息”:“无法执行语句;SQL[n/a];约束[email_exists_constraint];嵌套异常为org.hibernate.exception.constraintviolationexception:无法执行语句”“path”:“/api/v1/register”}

我错过了什么?如何达到预期的效果?

authController.java

@RestController
@RequestMapping("/api/v1")
public class AuthController {
...
@RequestMapping(value = "/register", method = RequestMethod.POST)
public User register(@Valid @RequestBody User user, BindingResult result) throws ValidationException {
    if (result.hasErrors()) {
        throw new ValidationException(result.getAllErrors());
    }
    return userRepository.save(user);
}

共有1个答案

时经纬
2023-03-14

在ExceptionControllerAdvice.java中使用@ResponseBody注释您的方法handleConflictException。这将告诉spring从返回对象生成一个JSON。@RestController在内部包含@ResponseBody,@ControllerAdvice不包含。

 类似资料:
  • 我正在使用org.springframework.data.jpa.repository.JpaRepository保存方法来保存一个实体。我认为保存方法来自CrudRepository接口。我从服务类调用这个保存方法。 但问题是< code > DataIntegrityViolationException 在catch块中没有被捕获。相反,我在下面的日志中看到。 和 我甚至尝试捕获Constr

  • 当我尝试使用以下命令将数据发布到我的REST API(使用Spring DATA JPA REST创建)时: 我得到这个错误:

  • 我有一个名为员工部的实体如下 我有一个Spring数据存储库,定义如下 此外,我注册了一个转换器,用于将字符串转换为EmployeeDepartmentPK。 现在,对于一个由ID employeeID=“abc123”和departmentCode=“JBG”限定的实体,我希望在调用SDR接口时使用的ID是abc123u JBG。例如http://localhost/EmployeeDepart

  • 通过使用JMockit@Capture,它无法捕获对任何Spring数据jpa存储库方法的调用。 然而,通过替换 用户存储库 具有 代码库 在测试类中,JMockit能够拦截对JpaRepository接口中可用的任何方法的调用,如findOne()或findAll()。 但它无法捕获对扩展JpaRepository的自定义存储库方法的调用,比如findByName()。 尽管基于JMockit状

  • 我使用的是Spring Boot 2和Spring Boot starter数据jpa以及底层的MariaDB。 我有一个带有唯一键“用户名”的表。如果违反了此约束,我想捕获,但似乎Spring正在记录并且不会在记录后重新抛出(我最好的猜测)。被抛出。 我想在中捕获。 以下是几段代码片段: 堆栈跟踪:

  • 问题内容: 是否可以在Java中构建一小段代码,以使假设的代码无法捕获? 想到的想法正在使用例如拦截器或面向方面的编程。 问题答案: 我没有试过,所以我不知道,如果JVM将限制这样的事情,但也许你可以编译代码抛出,但在运行时提供了一个类定义的其 未延伸的Throwable 。 更新: 没用 它生成一个验证错误: 更新2: 实际上,如果禁用字节码验证程序,则可以使它正常工作!() 更新3: 对于那些