尝试使用ControllerAdvice处理DataIntegrityViolationException并使用Spring Boot v 1.3.3&amp ;;返回自定义响应。 Spring Data REST v 2.4.4。这是我的课程:
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 “身份”:404 “错误”:“找不到” “exception”:“org.springframework.dao.DataIntegrityViolationException” “message”:“无法执行语句; 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);
}
答案 0 :(得分:1)
使用@ResponseBody在ExceptionControllerAdvice.java中注释方法handleConflictException。这将告诉spring从你的返回对象生成一个JSON。 @RestController里面有@ResponseBody,@ ControllerAdvice没有。