【发布时间】:2017-12-05 03:15:42
【问题描述】:
我想捕获在持久化过程中引发的所有异常到 DB(特别是 org.hibernate.exception.ConstraintViolationException)。 我正在使用 Spring 框架 4.3.8 Spring Data REST 2.6.3 和 Spring Data Jpa 1.11 + Hibernate 5.2.8。我的想法是利用@ControllerAdvice(或@RestController Advice)和@ExceptionHandler(Throwable.class) - 但我不能很好地捕捉到该死的异常。 请告诉我我的想法在哪一点是错误的。
好吧,我会让问题变得更容易。为什么这个异常处理不起作用? (但 /users/hello 路线将完美无缺。)
@RepositoryRestController
@RequestMapping("/users")
public class UsersController
{
@RequestMapping(value = "/hello/{variable}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<?> hello(@PathVariable String variable) throws Exception
{
if (variable.equals("1")) {
throw new Exception("my exception");
}
else {
return ok("hello world");
}
}
@ExceptionHandler
public String logErrors(Exception e) {
return "error: " +e.getMessage();
}
}
【问题讨论】:
-
你应该展示你的尝试。
-
@davidxxx 请告诉我你将如何实现它。没有代码 - 只是一个想法和你会使用什么注释(如果有的话)。
标签: java spring hibernate exception-handling spring-data-rest