java无法用Spring数据REST捕获DataIntegrityViolationException
尝试使用ControllerAdvice处理DataIntegrityViolationException,并使用Spring Boot v1.3.3&;返回自定义响应;弹簧数据REST v 2.4.4。以下是我的课程:
例外控制偏差。java
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(DataIntegrityViolationException.class)
public ViolationResponse handleConflictException(DataIntegrityViolationException ex) throws Exception {
return new ViolationResponse(ex.getMessage());
}
违规反应。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冲突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);
}
# 1 楼答案
在ExceptionControllerAdvice中注释方法handleConflictException。带有@ResponseBody的java。这将告诉spring从返回对象生成JSON@RestController中有@ResponseBody,@ControllerAdvice没有