[英]Spring Data REST @ExceptionHandler
我想捕获在持久化到数据库期间抛出的所有异常 (特别是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();
}
}
我已经解决了问题。 我的应用程序的主要配置是:
@Configuration
// other neccessary annotations
public class RestApplicationConfig extends RepositoryRestMvcConfiguration {
}
该项目纯粹是Spring Data Rest 。 要使用@ExceptionHandler
功能, 您需要运行Spring Web MVC 。 您可以通过以下两种方式之一进行操作:
1)将RepositoryRestMvcConfiguration导入到您的主要Spring Web MVC配置中:
@Configuration
@EnableWebMvc
// other neccessary annotations
@Import(RepositoryRestMvcConfiguration.class)
public class WebMvcConfig extends WebMvcConfigurerAdapter{}
2)当作为主要配置文件的类具有扩展RepositoryRestMvcConfiguration类的类时,请使用@EnableWebMvc
批注:
@Configuration
@EnableWebMvc
// other neccessary annotations
public class RestApplicationConfig extends RepositoryRestMvcConfiguration {}
值得补充的是,在Spring Data REST中,有一个标准的RepositoryRestExceptionHandler类,该类默认处理所有主要异常类型并对其进行日志记录。 因此,除非您需要更个性化的东西,否则您基本上不需要创建自己的处理程序。
关于什么:
@ExceptionHandler(org.hibernate.exception.ConstraintViolationException.class)
public String logErrors(Exception e) {
return "error: " +e.getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.