【发布时间】:2019-04-08 01:36:29
【问题描述】:
我一直无法捕捉到 ConstraintViolationException(或 DataIntegrityViolationException) 响应实体异常处理程序。 我想在响应中返回 jpa 失败(例如违反了哪个约束)。 (我不喜欢在方法参数上使用@Valid 并捕获handleMethodArgumentNotValid)。
...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;
@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {
...
return new ResponseEntity<Object>(...);
}
}
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class Student {
@Id
private Long id;
@NotNull
private String name;
@NotNull
@Size(min=7, message="Passport should have at least 7 characters")
private String passportNumber;
public Student() {
}
...
}
@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {
Student student = new Student();
student.setId(studentDto.getId()); // 1L
student.setName(studentDto.getName()); // "helen"
student.setPassportNumber(studentDto.getPassportNumber()); // "321"
studentRepository.save(student);
return ResponseEntity.accepted().body(student);
}
谢谢...
【问题讨论】:
-
你能试试 HibernateException 吗?只需更新此 @ExceptionHandler({HibernateException.class}) 并让我知道您的答案是什么......?
-
谢谢 - 虽然它没有解决问题。问题仍然存在。
-
哦,对了,我看了一下,并没有考虑像 ConstraintViolationException 这样的异常,因为它们是我认为的 HIbernateException 的扩展。所以 PersistenceException 而不是从 HibernateException 扩展的 AnyException 被抛出。所以我认为你应该更新这样的东西:@ExceptionHandler({PersistenceException.class}) public ResponseEntity
-
我在哪里/如何投票?谢谢
-
只需单击向上按钮此评论 xD 或有用的 cmets :)
标签: hibernate spring-mvc spring-boot spring-data-jpa