【问题标题】:Spring Data REST @ExceptionHandlerSpring Data REST @ExceptionHandler
【发布时间】: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


【解决方案1】:

我已经解决了这个问题。 我的应用程序主要配置是:

@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 类,它默认处理所有主要的异常类型并记录它们。因此,除非您需要更个性化的东西,否则您基本上不需要创建自己的处理程序。

【讨论】:

    【解决方案2】:

    怎么样:

    @ExceptionHandler(org.hibernate.exception.ConstraintViolationException.class)
    public String logErrors(Exception e) {
        return "error: " +e.getMessage();
    }
    

    【讨论】:

    • 是的,你的代码没问题,但问题是我项目中的另一件事 - 请参阅下面的答案
    猜你喜欢
    • 2015-06-22
    • 2011-09-10
    • 2016-10-26
    • 1970-01-01
    • 2015-12-17
    • 2018-12-10
    • 1970-01-01
    • 2017-09-16
    • 2014-10-06
    相关资源
    最近更新 更多