gpt4 book ai didi

java - 无法使用 Spring Data REST 捕获 DataIntegrityViolationException

转载 作者:行者123 更新时间:2023-11-30 07:22:54 26 4
gpt4 key购买 nike

尝试使用 ControllerAdvice 处理 DataIntegrityViolationException 并使用 Spring Boot v 1.3.3 和 Spring Data REST v 2.4.4 返回自定义响应。这是我的类(class):

ExceptionControllerAdvice.java

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

ViolationResponse.java

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;
}
}

我希望这会返回 409 Conflict HTTP 状态代码和消息

{"message" : "..."}

但是我收到了 404 状态,并收到了以下响应:

{ "timestamp": 1463382639043 "status": 404 "error": "Not Found" "exception": "org.springframework.dao.DataIntegrityViolationException" "message": "could not execute statement; SQL [n/a]; constraint [email_exists_constraint]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement" "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);
}

最佳答案

使用@ResponseBody注释ExceptionControllerAdvice.java中的handleConflictException方法。这将告诉 spring 从您的返回对象中生成 JSON。 @RestController 里面有 @ResponseBody,@ControllerAdvice 没有。

关于java - 无法使用 Spring Data REST 捕获 DataIntegrityViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com